【问题标题】:Fstream getline() only reading from the very first line of text file, ignoring every other lineFstream getline() 仅从文本文件的第一行读取,忽略每隔一行
【发布时间】:2021-07-29 10:57:35
【问题描述】:

我正在从事一个编码项目,我在其中对文本文件中的数据进行排序和组织,但我无法让 getline() 函数读取超过第一行。

我们的想法是捕获整行,将其分成 3 个部分,将其分配给一个对象,然后继续。除了让 getline() 正常工作之外,我什么都能做,这是我遇到问题的代码的 sn-p:

ifstream fin;
fin.open("textFile.txt");
while (!fin.eof()) // while loop to grab lines until the end of file is reached
{
    getline(fin, line); 
    fin >> first >> last >> pace; // assigning the data to their respective variables
    ClassObject obj(first, last, pace); // creating an object with those variables
    ClassVector.push_back(obj); // assignment object to vector
}

这是我最接近读取每一行的方法,同时还将数据排序到一个向量中,但正如我之前提到的,getline() 将读取第 1 行,并跳过文件的其余部分(1000 行)。

【问题讨论】:

  • firstlastpace 是如何定义的?
  • 它们在代码前面定义:string first, string last, int pace;
  • while 的第一次迭代将使用getline 读取第一行,然后下一个fin >> 将读取这三个变量,并可能完成下一行。第二个getline 会吃掉剩下的\nfin >> 会读到第三行。接下来,getline 吃掉剩下的 \n 等等。
  • 您正在阅读line,然后什么也不做。然后,您从下一行继续阅读firstlastpace。如果失败,则流有错误,eof 将返回 true,停止循环。
  • 总而言之:放弃eof检查(在你的整个职业生涯中,你可能永远找不到eof的好用处)并写while (fin >> first >> last >> pace) { ... }

标签: c++ fstream


【解决方案1】:

您可以做的不是使用!fin.eof()。我更喜欢使用类似的东西:

    ifstream file ( fileName.c_str() );

    while (file >> first >> last >> pace ) // assuming the file is delimited with spaces
    {
        // Do whatever you want with first, last, and pace
    }

“While 循环”将继续读取下一行,直到我们到达文件末尾。

如果 first,last,pace 的长度是恒定的,你也可以只获取该行的内容(在字符串变量中)并在其上使用子字符串,但这仅适用于在整个文件中长度是恒定的特定情况。

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 2019-05-06
    • 1970-01-01
    • 2017-11-20
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多