C++循环在 EOF 之后继续运行时这样做
C++ do while loop keeps going after EOF
我有一个关于文件 I/O 的问题。
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char** argv)
{
using namespace std;
string InputFileName="", temp=""; //File Name entered on command line
int Factor1=0, Factor2=0, MaxNum=0;
if (argc < 2)
{
cout << "No File Name Specifiedn";
return 0;
}
else
{
//InputFileName = argv[1]; //Get File Name from command line arguments array
ifstream inf (argv[1]); //open file for reading
if(!inf) //check for errors opening file, print message and exit program with error
{
cerr << " Error opening input filen";
return 1;
}
do
{
inf >> Factor1;
inf >> Factor2;
inf >> MaxNum;
cout << "Factor 1: " << Factor1 << " Factor 2: " << Factor2 << " Maximum Number: " << MaxNum << "n";
}while(inf);
}
return 0;
}
输入文件包含:
3 5 10
2 7 15
输出为:
Factor 1: 3 Factor 2: 5 Maximum Number: 10
Factor 1: 2 Factor 2: 7 Maximum Number: 15
Factor 1: 2 Factor 2: 7 Maximum Number: 15
这不是家庭作业。 我上C++课已经20年了。 我试图复习C++。 我职业生涯的大部分时间都在Visual Basic上工作。 我的问题是为什么 while 循环在输出第 3 行之前没有捕获 EOF 并退出,我该如何修复它,或者我以错误的方式解决这个问题。
您无法预测 I/O 是否会成功。您必须检查返回值:
while (inf >> Factor1 >> Factor2 >> MaxNum) // checks the value of "inf", i.e.
{ // whether the input succeeded
cout << "Factor 1: " << Factor1
<< " Factor 2: " << Factor2
<< " Maximum Number: " << MaxNum << "n";
}
您的原始代码鲁莽地假设输入在没有检查的情况下成功,继续使用输入,直到很久以后才回过头来问:"哦,顺便问一下,这些真的合法吗?
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 我在c++代码中生成了一个运行时#3异常
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 建议在运行时将带有类实例的列表从c++导入qml
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在程序继续C++时保持进程运行
- 阻止进程在从服务启动时启动,并在某些进程关闭后继续运行服务。
- 测试回文时程序不会继续运行 (C++)
- 在击中断点并继续执行VS时,如何在运行时自动修改变量的值
- C++循环在 EOF 之后继续运行时这样做
- 为什么我的代码在运行时继续崩溃
- QT/C++,OS X:退出应用程序时可选择隐藏(),以便应用程序继续运行,并在单击dock中的图标后再次显示
- FindFirstFile在加密时继续运行相同的文件