getline函数只读取第一行
问题描述:
这是我的程序。它应该从输入文件读取每行并以整洁的格式显示在控制台上。但是,getline只读取第一行。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结束位将被设置。在下一个循环开始时重置字符串不会重置该位,因此它仍将被设置。当您尝试第二次提取时,流认为它已经在文件的末尾,并且认为它没有任何可读的内容,因此它会提前出局。清除状态位修复了这一点。
哦,非常感谢。 – 2015-03-31 21:04:48