小编Lew*_*wis的帖子

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

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

cin>>filename;
ifstream workingfile(filename);

while (workingfile>>int1>>int2>>string1>>string2) {
    cout<<int1<<int2<<string1<<string2<<endl;
    linenumread++;
}
Run Code Online (Sandbox Code Playgroud)

我尝试过,但它不起作用,任何帮助将不胜感激

 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++;
}
Run Code Online (Sandbox Code Playgroud)

还有可能检测它是否也停止读取字符串?

输入文件看起来像这样

10 10 ab bc
11 11 cd ef
a  
12 12 gh hi
Run Code Online (Sandbox Code Playgroud)

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

c++ ifstream while-loop

0
推荐指数
1
解决办法
615
查看次数

标签 统计

c++ ×1

ifstream ×1

while-loop ×1