简体   繁体   中英

error about using ifstream in loop

I have a very simple code and the functionality of it is to type in the name of the file from which the program will read data. Since the file might not be correct due to mistyping, the console will continue to ask the user to type in the name if the previous name is invalid.

The issue is, while the first do-while loop works fine, the program will skip the second while loop if the name of the file is not correctly typed in for the first time in the first loop. However, if the name of the file is typed in correctly, everything works fine.

I wonder why the program behaves like this.

Thanks for your help and your time!

#include<iostream>
#include<fstream>

using namespace std;

int main() {
    string context;
    int step=0,i=0;
    ifstream fin;

    do {
        string filename;
        cout << endl << "please type in the name of input file" << endl;
        cin >> filename;
        string filepath = "files/" + filename;
        cout << filepath << endl;
        fin.open( filepath.c_str() );
    } while( !fin.is_open() );

    while (getline(fin, context)){
        cout << context << endl;
        cout << "hello" << endl;
    }
    fin.close();
    return 0;
}

I think that the state of "fin" might be tainted after the first try. Why dont you try calling fin.clear() before the call to fin.open().

您需要清除您的ifstream,它可能被先前的文件尝试损坏。

From the standard,

27.8.1.10
void open(const char* s, ios_base::openmode mode = ios_base::out);
Calls rdbuf()->open(s,mode|out) . If that function returns a null pointer, calls setstate(failbit). 311a

So what's this note 311a?

311a A successful open does not change the error state.

While notes are not normative, the normative text says absolutely nothing about what a successful open does to the error state if the rdbuf->open() was successful. The note clarifies this non-statement.

Bottom line: You need to clear the file stream's status bits prior to calling open when you are re-calling open after it failed.

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