getline()如何工作?

时间:2011-04-09 20:28:15

标签: c++ getline

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

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

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

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

     current->insert(student);
}

2 个答案:

答案 0 :(得分:3)

  

它总是加载额外的行

当然:您正在插入已阅读的内容而未验证 是否已成功阅读。

您需要在读取尝试后移动file.good()测试

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

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

答案 1 :(得分:2)

getline()读取\ n或EOF终止行。

所以在二进制文件中它并没有多大意义。

  

提取字符直到   (n - 1)个字符已被提取   或找到分隔字符   (如果此参数为,则为delim   指定,否则为“\ n”。该   如果结束,提取也会停止   在输入序列中到达文件   或者如果在输入过程中发生错误   操作