while循环中的std :: bad_alloc错误

时间:2012-10-25 22:06:05

标签: c++

Noob在这里。我知道我不应该发布作业,但我不知道可能导致这个问题的原因。由于某种原因,这个while循环在它退出之前抛出一个std :: bad_alloc异常(即当它读取文件结尾时)。它只在8GB的系统上使用500 MB的RAM,所以我很确定它不会过度使用内存。如果有人可以提供帮助,那就太棒了,因为我现在已经搜索了这个问题大约四个小时,但找不到修复方法。这可能是愚蠢的,但我无法弄明白。

以下是代码:

temperatures_in >> low >> high;
tempMin=low;
tempMax=high;
getLocation(temperatures_in, location);

while(!temperatures_in.eof()){
    temperatures_out << left << setw(20) << location;
    temperatures_out << right << fixed << showpoint << setprecision(2) << setw(6) << low << setw(6) << high << endl;
    temperatures_in >> low >> high;
    getLocation(temperatures_in, location);
    if(low<tempMin){
        tempMin=low;
    }
    if(high>tempMax){
        tempMax=high;
    }
    cout << low << " " << tempMin << " " << high << " " << tempMax << " " << location;
}

此外,当我运行调试器时,它显示异常以某种方式被抛出-1行(即使可能?),即使我已经测试了循环内外的输出,它将在结束前执行代码循环,但不是之后。

编辑:这是getLocation()函数:

void getLocation(ifstream &temperatures_in, string &location){
    char a;
    temperatures_in.get(a);
    while(a==' '){
        temperatures_in.get(a);
    }
    location="";
    while(a!='\n'){
        location+=a;
        temperatures_in.get(a);
    }
}

0 个答案:

没有答案
相关问题