如何在 for 循环中使用 eof 迭代整数 c++
这给了我一个分段错误:
for (int i=0; !file.eof();i++)
{
getline(file,line);
roughInput.lines[i].split(line);
}
根据我的理解,这并不
for (int i=0; i<2;i++)
{
getline(file,line);
roughInput.lines[i].split(line);
}
应该将 i 加一直到文件末尾,对吗? 由于我在网上找不到太多示例,有更好的解决方案吗?
this gives me a segmentation fault:
for (int i=0; !file.eof();i++)
{
getline(file,line);
roughInput.lines[i].split(line);
}
and this doesn't
for (int i=0; i<2;i++)
{
getline(file,line);
roughInput.lines[i].split(line);
}
from my understanding for should increase i by one until the end of file, right?
since i couldn't find much example on i-net, is there a better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的循环可能运行了太多次。
file.eof()
直到您尝试读取文件末尾时才会返回 false。您可能希望将检查放在getline
调用和split
: 之间,并相应地修复循环逻辑。
然而,更好的解决方案是动态增长
roughInput.lines
,这样,如果文件比您预期的长,您就不会出现段错误。Your loop is probably running one time too many.
file.eof()
will not return false until after you have tried to read while you are at the end of the file. You probably want to put the check in between thegetline
call and thesplit
:and fix the loop logic accordingly.
However, a better solution would be to grow
roughInput.lines
dynamically, so that you don't get a seg fault if the file is longer than you expect.