简体   繁体   English

关于在循环中使用ifstream的错误

[英]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. 问题是,虽然第一个do-while循环运行良好,但如果在第一个循环中第一次未正确输入文件名,则程序将跳过第二个while循环。 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(). 为什么不尝试在调用fin.open()之前先调用fin.clear()。

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

From the standard, 从标准来看

27.8.1.10 27.8.1.10
void open(const char* s, ios_base::openmode mode = ios_base::out);
Calls rdbuf()->open(s,mode|out) . 调用rdbuf()->open(s,mode|out) If that function returns a null pointer, calls setstate(failbit). 如果该函数返回空指针,则调用setstate(failbit)。 311a 311A

So what's this note 311a? 那么,这条笔记311a是什么?

311a A successful open does not change the error state. 311a成功打开不会更改错误状态。

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. 尽管注释不是规范性的,但是如果rdbuf->open()成功,则规范性文本完全没有说明成功打开对错误状态rdbuf->open() 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. 底线:你需要clear在调用文件流的状态位open ,当你重新调用open后失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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