gpt4 book ai didi

c++ - getline() 是如何工作的?

转载 作者:行者123 更新时间:2023-11-30 01:29:37 27 4
gpt4 key购买 nike

我有这段代码用于从二进制文件或文本文件加载链表。它对文本文件工作正常,但它总是在二进制情况下加载额外的一行,所以我需要知道如何getline 工作:

while(1)
{
if(!file.good())
break;

getline(file,line);
student.name=line;

getline(file,line);
student.phone=line;

current->insert(student);
}

最佳答案

it always loads an extra line

当然:您插入的是您已阅读的内容,而没有验证它是否已成功阅读。

您需要在阅读尝试之后移动您的file.good() 测试。

此外,无需显式测试 goodgetline 的结果已经为您提供了状态。在循环中从文件加载简单数据的规范方法如下:

student_type student;
while (getline(file, student.name) and getline(file, student.phone))
current->insert(student_type(student)); // Makes explicit copy!

关于c++ - getline() 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5607690/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com