我正在尝试从特定行(第 1、7、13 等 - 所需数据放在下一个第 6 行)中的文本文件中获取一些数据
到目前为止我的代码是这样的:
txtfile = "titles.txt";
ifstream txt(txtfile);
const int buffer_size = 80;
char title_buffer[buffer_size];
const int titleLineDiff = 6;
if (txt.is_open())
{
while(!txt.eof())
{
static int counter = 1;
txt.getline(title_buffer, buffer_size);
cout << "Title: \"" << counter << "." << title_buffer << "\"" << endl;
counter++;
//seek to the next title...difference is 6 lines
for(int i = 0; i < titleLineDiff; i++)
txt.getline(title_buffer, 40);
}
}
现在,它可以很好地处理我创建的这个文件:
testONE
two
three
four
five
six
testTWO
bla
它打印“testONE”和“testTWO”但是当我试图打开包含数据的文件时,我得到一个无限循环并且输出是
Title: "counter_increasing_number."
文本文档,是从网上复制过来的,可能是阅读问题的原因。
我该怎么办?
我已将代码更改为:
while(getline(txt,title_buffer))
{
static int counter = 1;
//getline(title_buffer, buffer_size);
cout << "Title: \"" << counter << "." << title_buffer << "\"" << endl;
counter++;
//seek to the next title...difference is 6 lines
for(int i = 0; i < titleLineDiff; i++)
{
getline(txt, title_buffer);
}
}
它奏效了。
有人可以向我解释第一个不起作用的原因吗?
最佳答案
对于初学者,您正在使用 getline
的结果
检查是否成功。 (在第二个版本中,这是
仅适用于内部循环。)
至于第一个版本错误的原因:是否设置了eof
在最后一次成功读取之后,或者在第一次不成功之后,
没有真正指定。当然,还有其他原因
输入可能会失败,除了文件结尾。神圣的成语
是总是使用getline
(和任何其他输入)作为
循环或 if 中的控制表达式。如果表达式是
认为true
,输入成功。它是有时
在知道输入失败后检查 eof()
很有用;
如果 eof()
不正确,则问题出在其他地方:
硬件错误(bad()
为真)或
格式。
至于为什么你的测试数据和实际数据表现不同, 没有看到两者就很难说。一些可能的原因: 不同的行结束约定,可能是一组数据 以不完整的行结尾(如果数据已被 使用 Windows 编辑器生成)或比您的行长的行 缓冲区(在你的第一种情况下)。
关于c++ - 当检查是eof时,使用getline读取文本文件会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15101453/