gpt4 book ai didi

c++ - getline 函数只读取第一行

转载 作者:行者123 更新时间:2023-11-28 02:29:33 26 4
gpt4 key购买 nike

这是我的程序。它应该从输入文件中读取每一行并以整洁的格式显示在控制台上。然而,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 位将被设置。在下一个循环开始时重置字符串不会重置该位,因此它仍将被设置。当您第二次尝试提取时,流认为它已经在文件末尾并且认为它没有任何内容可读,因此它提前退出。清除状态位可以解决这个问题。

关于c++ - getline 函数只读取第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29377882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com