getline函数只读取第一行

The getline function only reads the first line

本文关键字:一行 函数 读取 getline      更新时间:2023-10-16

这是我的程序。它应该从输入文件中读取每一行,并以整洁的格式显示在控制台上。但是,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

第二次循环后,缓冲区提取失败,因为您没有清除状态位。这样做:

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

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

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

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