Search code examples
c++ifstreamgetline

The getline function only reads the first line


This is my program. It is supposed to read each line from an input file and display on the console in a neat format. However, the getline only reads the 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 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;
    }
}

The input file looks like 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 it displays as this (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

Solution

  • The buffer is failing to extract after the second loop, because you have not cleared the status bits. Do this:

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

    You can see this by adding some output to your code:

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

    after the first time through your loop, the stream with reach the end of the input string and the EOF bit will get set. Resetting the string at the beginning of the next loop doesn't reset this bit, so it will still be set. When you try to extract the second time, the stream thinks it is already at the end of the file and thinks it doesn't have anything to read, so it early-outs. Clearing the status bits fixes this.