getline函数只读取第一行
The getline function only reads the first line
这是我的程序。它应该从输入文件中读取每一行,并以整洁的格式显示在控制台上。但是,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位将被设置。在下一个循环开始时重置字符串不会重置此位,因此它仍将被设置。当您尝试第二次提取时,流认为它已经在文件的末尾,并且认为它没有任何内容可读取,因此它提前退出。清除状态位可修复此问题。
相关文章:
- 如何使用运算符在同一行中多次调用函数
- uncrustify:如何将多行 C 函数调用的参数组合到一行上?
- 使用更改此变量的函数在同一行中打印引用变量
- Ofstream一直给我函数的最后一行,而不是显示所有内容
- C++将函数指针放入一行的映射中
- C++ 两个函数除了一行之外执行相同的操作
- 将地址返回到 2D 数组中的一行值的函数
- 无法理解代码的特定片段:这是一个函数,只是一行还是什么
- 线程1:EXC_BAD_ACCESS错误,此错误在第一行的CPP文件中的句柄函数中出现
- 当两个函数位于一行中时,堆栈框架的样子
- 如何将具有多行代码的内联函数视为一行?
- 为什么这个函数从不超出第一行
- 无法弄清楚为什么只从文件中读取一行矩阵以及为什么我无法将 2D 数组传递给函数
- clang format函数和错误检查在同一行
- 从函数结果中分配 std::shared_ptr 的一行是什么?
- 当const在另一行处的const时,doxygen parse const成员函数不正确
- 为什么在同一行上有 2 个函数调用时跳过函数调用
- 在文件中返回一行的函数
- getline函数只读取第一行
- C++ 函数删除一行