Search code examples
c++ifstreamgetline

In C++ why is ifstream getline returning every other number in my .txt file, rather than all of them?


When I run this code it doesn't print the contents of the .txt file which is numbers 1 to 100, it prints all of the even numbers up to 100 (e.g. 2 4 6 8 so on.) And I don't know why, it didn't before and I don't think I changed anything. I'm using xcode. Anybody got any ideas?

#include <stdio.h>     
#include <iostream>     
#include <cmath>        
#include <string>       
#include <sstream>      
#include <fstream>


using namespace std;

int main () {
    string line;
    int Points[100];
    ifstream myfile("StatNum.txt");
    if (myfile.is_open())
    {
        while ( getline (myfile,line) )
        {
            getline(myfile,line);
            stringstream(line) >> Points[100];  //uses stringstream to convert Myline (which is a string) into a number and put it into an index of Points
            cout << Points[100] << endl;
        }
        myfile.close();
    }

    else cout << "Unable to open file" << endl;

    return 0;
}

Solution

  • This happens because you call getline twice per iteration:

    • First, you call it in the while header
    • Then you call it inside the loop.

    One invocation (the one in the while header) is sufficient, because the result is saved in the line variable, which the loop body is free to examine.

    Removing the second invocation will fix the problem.