getline() 读取额外的一行
ifstream file("file.txt");
if(file.fail())
{
cout<<"Could not open the file";
exit(1);
}
else
{
while(file)
{
file.getline(line[l],80);
cout<<line[l++]<<"\n";
}
}
我使用二维字符数组来保留从文件中读取的文本(多于一行),以计算文件中的行数和单词数,但问题是 getline 总是读取额外的行。
ifstream file("file.txt");
if(file.fail())
{
cout<<"Could not open the file";
exit(1);
}
else
{
while(file)
{
file.getline(line[l],80);
cout<<line[l++]<<"\n";
}
}
I am using a two dimensional character array to keep the text (more than one line) read from a file to count the number of lines and words in the file but the problem is that getline always reads an extra line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我正在编写的代码:
第一次
getline
失败时,您仍然会增加行计数器并输出(不存在的)行。始终检查是否有错误。
额外建议:使用
标头中的std::string
,并使用其getline
函数。干杯&嗯。
Your code as I'm writing this:
The first time
getline
fails, you still increment the line counter and output the (non-existing) line.Always check for an error.
extra advice: use
std::string
from the<string>
header, and use itsgetline
function.cheers & hth.
问题是,当您到达文件末尾时,对
file
的测试仍然会成功,因为您尚未读到文件末尾。因此,您还需要测试getline()
的返回。由于您需要测试
getline()
的返回值以查看是否成功,因此您也可以将其放在 while 循环中:这样您就不需要对
进行单独的测试文件
和getline()
。The problem is when you're at the end of the file the test on
file
will still succeed because you have not yet read past the end of file. So you need to test the return fromgetline()
as well.Since you need to test the return from
getline()
to see if it succeeded, you may as well put it right in the while loop:This way you don't need a separate test on
file
andgetline()
.这将解决您的问题:
它更强大
This will solve your problem:
Its more robust
仅当
file.good()
为 true 时才执行cout
。您看到的额外行来自最后一次调用file.getline()
,该调用读取了文件末尾。Only do the
cout
iffile.good()
is true. The extra line you're seeing comes from the last call tofile.getline()
which reads past the end of the file.文件是否以换行符结尾?如果是这样,则直到经过一个额外的循环后才会触发 EOF 标志。例如,如果文件是
那么循环将运行3次,第一次将得到
abc
,第二次将得到def
,第三次将得到def
将一无所获。这可能就是您看到额外一行的原因。尝试在 getline 之后检查流上的失败位。
Does the file end with a newline? If it does, the EOF flag will not be triggered until one extra loop passes. For example, if the file is
Then the loop will be run 3 times, the first time it will get
abc
, the second time it will getdef
and the third time it will get nothing. That's probably why you see an additional line.Try checking the failbit on the stream AFTER the getline.