【问题标题】:getline() reads an extra linegetline() 读取额外的一行
【发布时间】:2011-09-29 12:39:10
【问题描述】:
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 总是读取额外的一行。

【问题讨论】:

标签: c++ ifstream getline


【解决方案1】:

我正在写的代码:

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 第一次失败时,您仍然会增加行计数器并输出(不存在的)行。

始终检查错误。

额外建议:使用 &lt;string&gt; 标头中的 std::string,并使用其 getline 函数。

干杯&hth。

【讨论】:

    【解决方案2】:

    问题是当你在文件末尾时,file 上的测试仍然会成功,因为你还没有读到文件末尾。所以你还需要测试来自getline() 的返回。

    既然要测试getline()的返回是否成功,不妨直接放在while循环中:

    while (file.getline(line[l], 80))
        cout << line[l++] << "\n";
    

    这样您就不需要对filegetline() 进行单独测试。

    【讨论】:

      【解决方案3】:

      这将解决您的问题:

      ifstream file("file.txt");
      if(!file.good())
      {
        cout<<"Could not open the file";
        exit(1);
      }
      else
      {
        while(file)
        {
          file.getline(line[l],80);
             if(!file.eof())
                cout<<line[l++]<<"\n";
        } 
      }
      

      它更强大

      【讨论】:

        【解决方案4】:

        文件是否以换行符结尾?如果是这样,EOF 标志将不会被触发,直到一个额外的循环通过。例如,如果文件是

        abc\n
        def\n
        

        然后循环会运行 3 次,第一次会得到abc,第二次会得到def,第三次会什么都没有。这可能就是您看到额外一行的原因。

        尝试在 getline 之后检查流上的故障位。

        【讨论】:

          【解决方案5】:

          仅当file.good() 为真时才执行cout。您看到的额外行来自对 file.getline() 的最后一次调用,它读取到文件末尾。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-24
            • 1970-01-01
            • 1970-01-01
            • 2015-06-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-05
            相关资源
            最近更新 更多