提问人:Zhao Dazhuang 提问时间:8/3/2022 最后编辑:Zhao Dazhuang 更新时间:8/6/2022 访问量:58
当文件中的行数小于 C++ 中目标中读取的行数时,如何中止?
How to abort when the number of rows in the file is less than the number of rows read in the target in C++?
问:
现在我有一个像这样的 txt 文件:
5
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
5
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
...
此文件的一个循环是 7 行,7 行中的第二行是空行。我的文件一共有5个循环,但是当我的代码设置为读取10个循环时,代码不会报错,我应该如何修改代码报错在文件末尾,注意我的文本文件出现一个空行。
#include<fstream>
#include<string>
int main()
{
std::ifstream get_in("tst.txt", std::ios :: in );
for ( int loop=0;loop<10;loop++ )
{
std::string line;
for ( int i=0;i<7;i++ )
{
getline(get_in, line);
}
}
return 0;
}
这是我代码的一个简化示例,我希望它在文本不足以满足我想要读取的行数时出错,而不是正常运行。
答:
0赞
Scott
8/6/2022
#1
检查输入流的 eof 位,这可以通过直接访问它 get_in.eofbit 或使用 eof() 函数 get_in.eof
()
来完成。
我建议使用 eof()
函数。
我不确定你对你的代码做了什么,但这里有一个简单易懂的代码修改作为演示:
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::ifstream get_in("tst.txt", std::ios :: in );
std::string line;
for ( int loop=0;loop<10;loop++ )
{
if(get_in.eof()) { std::cout << "EOF"; break; }
for ( int i=0;i<7;i++ )
{
std::getline(get_in, line);
if(get_in.eof()) break;
std::cout << line << std::endl;
}
}
return 0;
}
评论
break;