简体   繁体   中英

End of file and while-loop

I have a c++ code snippet that is supposed to read some information from a file, and failing to find the file or the information, read it from screen. Here's the code:

char c;
bool found=false;
int N;
double step;
ifstream in;
in.open(name.c_str());
if(in) {
    while(!found && in >> c) {
        while(c!='=') in >> c;
        in >> N;
        if(N==wp.N) {
            found=true;
            while(c!=':') in >> c;
            in >> step;
        }
        c='a';
    }
}
if(!found) {
    cout << "max=";
    cin >> step;
}

The above is constructed according to the structure of the data in the file, and everything works when the information is in the file (ie N=wp.N at some point) or the file doesn't exist (ie if(in) is not true).

But the problem arises when the file exist but doesn't contain the info, that is N==wp.N is never true. Then the program freezes (presumably at the end of the file, so that found is never true). I was expecting that including in >> c inside the while -loop would fix this, but I've also tried using in.eof() .

Any suggestions?

You may find eof() after any of your in >>.

So I'd assume you're looping on while(c!=':') or while(c!='=')

The problem is in your second loop, which will loop infinitely if you reach end of file without reading a '=' . You need the in >> c in the condition there as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM