c++ - The getline function only reads the first line -
this program. supposed read each line input file , display on console in neat format. however, getline reads first line.
#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 open input file 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; } } the input file looks this:
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 but displays (before being organized):
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
the buffer failing extract after second loop, because have not cleared status bits. this:
buffer.clear() buffer.str(line); you can see adding output code:
std::cout << "eof: " << buffer.eof() << std::endl; after first time through loop, stream reach end of input string , eof bit set. resetting string @ beginning of next loop doesn't reset bit, still set. when try extract second time, stream thinks @ end of file , thinks doesn't have read, early-outs. clearing status bits fixes this.
Comments
Post a Comment