0

I am having trouble parsing my text file which is separated my commas. istream and ifstream really confuse me.

Here is my text file:

2,2,Robin Williams
3,2,Bud Abbott,Lou Costello
4,2
5,4,Groucho,Chico,Harpo,Gummo
6,3
7,2,W.C. Fields
9,5

and here is my code

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream inf("test.txt");
    while(!inf.eof())
    {
        string line;
        int roomNumber;
        inf >> roomNumber;
        getline(inf, line);
        cout << roomNumber << endl;
    }
}

My end goal is to separate each field by commas and store them somewhere. The first two numbers will always be therre while the names can be empty. Right now I am just trying to store the first integer, the roomNumber, and printing them out but my output looks like this:

2
3
4
5
6
7
9
9

Why are there two nines and is there any better way to do this?

It's literally more specific and different.

Apple
  • 401
  • 1
  • 4
  • 7
  • [while(!inf.eof())](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong). – user657267 Mar 17 '15 at 05:38
  • There are two 9's in your output because you loop one more time after reading the 9 line, but this time your inputs fail and the `roomNumber` you print is garbage that is left over on the stack from your previous loop iteration and just so happens to be 9. – jschultz410 Mar 17 '15 at 05:44

0 Answers0