while(in) 和 while(!in.eof()) 之间的区别?
我有这个 readFile 函数。
void readFile(People peps[], int& cnt)
{
ifstream in("people.txt");
if (!in)
{
cout << "Error opening file\n";
}
else {
while (in) //1
while (!in.eof())//2
{
getline(in, peps[cnt].fullname, '-');
getline(in, peps[cnt].h, '-');
getline(in, peps[cnt].w, '\n');
++cnt;
}
in.close();
}
}
while(in) 和 while(!in.eof()) 之间有什么区别?之前,我使用 while(!in.eof()) 来检测文件末尾,但后来我看到我的讲师使用 while (in) 代替。我认为它们是相同的,但似乎 while(in) 甚至在文件末尾又读取了一行?
我的 people.txt 文件有 97 行,因此 while 循环执行完毕后 cnt
应为 97。由于某种原因,当我使用 while(in) 时,cnt
以 98 结尾,而 peps[97]
存储空字符串。
I have this readFile function.
void readFile(People peps[], int& cnt)
{
ifstream in("people.txt");
if (!in)
{
cout << "Error opening file\n";
}
else {
while (in) //1
while (!in.eof())//2
{
getline(in, peps[cnt].fullname, '-');
getline(in, peps[cnt].h, '-');
getline(in, peps[cnt].w, '\n');
++cnt;
}
in.close();
}
}
What is the difference between while(in) and while(!in.eof())? Before, I used while(!in.eof()) to detect the end of a file but then I saw my instructor use while (in) instead. I thought they were the same but it seems while(in) reads one more line even at the end of the file?
My people.txt file has 97 lines so cnt
should be 97 after the while loop finishes executing. For some reason, when I use while(in), cnt
ends up with 98, and peps[97]
stores empty strings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
while(in) 条件包括导致文件不可读的所有原因,而不仅仅是 eof。
我很困惑为什么这会导致额外的线路。也许文件的最后一行不以换行符结尾?
The
while(in)
condition includes all the reasons that make the file unreadable, not just eof.I'm perplexed why that would result in an extra line. Maybe the last line of your file doesn't end with a newline character?
特殊功能-> eof(),当没有更多数据可从输入文件流中读取时,返回非零(表示 TRUE),否则返回零(表示 FALSE)。
special function-> eof(), that returns nonzero (meaning TRUE) when there are no more data to be read from an input file stream, and zero (meaning FALSE) otherwise.