【问题标题】:The getline function only reads the first linegetline 函数只读取第一行
【发布时间】:2015-06-05 08:06:46
【问题描述】:

这是我的程序。它应该从输入文件中读取每一行并以简洁的格式显示在控制台上。但是,getline 只读取第一行。

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <sstream>
using namespace std;

int main(int argc, char *argv[]){
    ifstream inFile;
    string state, quantityPurchased, pricePerItem, itemName;    
    inFile.open("lab11.txt");
    if (inFile.fail()){
        perror ("Unable to open input file for reading");
        return 1;
    }
    string line;
    istringstream buffer;
    while(getline(inFile, line)){
        buffer.str(line);
        buffer >> state >> quantityPurchased >> pricePerItem >> itemName;

        cout << left << setw(2) << state << " ";
        cout << setw(15) << itemName << " ";
        cout << right << setw(3) << quantityPurchased << " ";
        cout << setw(6) << pricePerItem << endl;
    }
}

输入文件如下所示:

TX 15 1.12 Tissue
TX 1 7.82 Medication
TX 5 13.15 Razors
WY 2 1.13 Food
WY 3 3.71 Dinnerware

但它显示为这样(在组织之前):

TX 15 1.12 Tissue
TX 15 1.12 Tissue
TX 15 1.12 Tissue
TX 15 1.12 Tissue
TX 15 1.12 Tissue

【问题讨论】:

    标签: c++ ifstream getline


    【解决方案1】:

    缓冲区在第二次循环后无法提取,因为您尚未清除状态位。这样做:

    buffer.clear()
    buffer.str(line);
    

    您可以通过在代码中添加一些输出来看到这一点:

    std::cout << "EOF: " << buffer.eof() << std::endl;
    

    第一次通过循环后,流到达输入字符串的末尾并且 EOF 位将被设置。在下一个循环开始时重置字符串不会重置该位,因此仍会设置它。当您尝试第二次提取时,流认为它已经在文件的末尾并且认为它没有任何要读取的内容,所以它提前了。清除状态位可以解决这个问题。

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2021-01-26
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多