使用ifstreamwhile循环,如何显示输入错误并在下一行继续
With ifstream while loop, how to show an input error and resume at the next line?
如果我的输入文件以字母开头,它将停止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++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 从C++dll访问C#中的一行主要参数
- 在C++中,我如何接受不同于同一行的用户输入
- 我正在尝试使用 c++ 创建一个货币转换程序,我不知道如何继续
- 如何从一行中读取特定数量的字符?(C++)
- C++:继续创建新的变量可以吗
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 有没有办法在一行中填充矢量图
- 需要将一行代码从C++ Qt翻译成PyQt
- 为什么如果我添加这一行,我的程序会不断询问值
- 如何使代码打印文本文件中的第一行?
- 如何在C++中以这种方式返回一行文本?
- 在C++编程中继续下一行的另一种方法是什么?
- 使用ifstreamwhile循环,如何显示输入错误并在下一行继续
- CIN 并继续在一行中用逗号分隔
- 在反斜杠后面是否允许空格来继续一行(在C/ c++中)