c++ - 使用 ifstream while 循环,如何显示输入错误并在下一行继续?

标签 c++ while-loop ifstream

如果我的输入文件以字母开头,它将停止 while 循环,因为它无法重写 int1,我知道这一点,但我如何能够检测到这一点并显示一条错误消息,指出 workinfile>>int1 没有工作然后继续循环?

cin>>filename;
ifstream workingfile(filename);

while (workingfile>>int1>>int2>>string1>>string2) {
    cout<<int1<<int2<<string1<<string2<<endl;
    linenumread++;
}

我试过了,但是没有用,如果有任何帮助,我们将不胜感激

 while (workingfile>>int1>>int2>>string1>>string2) {
    if(!(workingfile>>int1))
    {
       cout<<"Error first value is not an integer"<<endl;
       continue;
    }
    cout<<int1<<int2<<string1<<string2<<endl;
    linenumread++;
}

是否也可以检测它是否也停止读取字符串?

输入文件看起来像这样

10 10 ab bc
11 11 cd ef
a  
12 12 gh hi

我想检测它何时遇到无效输入,显示错误消息,然后继续文件中的下一行。

最佳答案

对于这种输入,通常最好读取整行,然后从该行中提取值。如果无法解析该行,您可以报告该行失败,然后从下一行的开头继续。

看起来像这样:

std::string line;
while (std::getline(workingfile, line)) // Read a whole line per cycle
{
    std::istringstream workingline(line); // Create a stream from the line
    // Parse all variables separately from the line's stream
    if(!(workingline>>int1))
    {
       cout<<"Error first value is not an integer"<<endl;
       continue;
    }
    if(!(workingline>>int2)
    {
       cout<<"Error second value is not an integer"<<endl;
       continue;
    }
    // ^^^^ a.s.o. ...
    cout<<int1<<int2<<string1<<string2<<endl;
    linenumread++;
}

关于c++ - 使用 ifstream while 循环,如何显示输入错误并在下一行继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47291977/

相关文章:

c++ - std::atomic<uint_least8_t> 行为

c++ - 可以将多维 std::array 视为连续的数据 block 吗?

php - 在 php 中使用 css 样式

c - C 中的 for/while 循环内存清除

c++ - 在 C++ 中按行读取大文件

c++ - 读入单词搜索游戏 C++ 的文件

c++ - 为什么在使用 `std::views::reverse` 时对过滤函数进行了多余的调用?

c++ - cout << hex 与 uint8 和 uint16 的行为

c - 如何找到输入的长度

c++ - 用于加载文件的 while 循环不起作用