简体   繁体   English

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

[英]With ifstream while loop, how to show an input error and resume at the next line?

If my input file started with a letter it will stop the while loop because it cant rewrite int1 , I know that but how would I be able to detect this and show an error message saying that workinfile>>int1 did not work and afterwards continue the loop? 如果我的输入文件以字母开头,它将停止while循环,因为它无法重写int1 ,我知道,但是我将如何检测到它并显示一条错误消息,指出workinfile>>int1无法正常工作,然后继续环?

cin>>filename;
ifstream workingfile(filename);

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

I tried doing but it doesn't work, any help would be appreciated 我尝试这样做,但是它不起作用,我们将不胜感激

 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++;
}

Also would it be possible to detect if it stops reading the strings as well? 还可以检测它是否也停止读取字符串吗?

The input file would look like this 输入文件如下所示

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

I want to to detect when it hits an invalid input, show an error message, and continue with the next line in the file. 我想检测它何时击中无效输入,显示错误消息并继续文件中的下一行。

For this kind of input, it's usually better to read a complete line, and then extract the values from that line. 对于这种输入,通常最好阅读完整的一行,然后从该行中提取值。 If the line can't be parsed, you can report a failure for that line, and just continue from the start of the next line. 如果无法解析该行,则可以报告该行的失败,然后仅从下一行的开头继续。

That would look something like this: 看起来像这样:

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++;
}

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

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