0

I'm having trouble understanding how to read the lines of a text file, and then breaking each line into integers and strings. Here is what my read.txt looks like:

ID   Name 
1234 name1
ID   Name  
5678 name2 
9101 name3
ID   Name 
1121 name4 
3141 name5

I skip the header "ID Name" by checking each line for that string.

EDIT (I changed my code to this and the values seem to be getting stored).

ofstream write2 ("write2.txt");
ifstream infile ("read.txt");
string header = "ID   Name";
string strVal;
string str;
int intVal;
vector <int> ID;
vector <string> NAME;

if ( infile.is_open() )
{
    while ( !infile.eof() )
    {
        getline(infile, str);
        istringstream ssin(str);

        ssin >> intVal >> strVal;
        ID.push_back(intVal);
        NAME.push_back(strVal);

    }
}

for ( int i = 0; i < (int)ID.size(); i++ )
    cout << endl << NAME[i] << "\t" << ID[i] << endl;

The values are being stored in my vectors now, but I do not completely understand why the stringstream works the way it does.

Raj Patel
  • 35
  • 4
  • Possible duplicate of [How to extract mixed format using istringstream](http://stackoverflow.com/questions/21814297/how-to-extract-mixed-format-using-istringstream) – ShadowMitia Apr 24 '16 at 20:00
  • 1
    [`while ( !infile.eof() )`](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) isn't such a good idea. – πάντα ῥεῖ Apr 24 '16 at 20:02
  • How did you determine that the results aren't getting stored? Your sample code doesn't display any results. – Pete Becker Apr 24 '16 at 20:02
  • @πάνταῥεῖ Is there a better way of going about checking for the end of the file? Is it possible to put the getline function in the while-loop, or is that also bad practice? – Raj Patel Apr 24 '16 at 20:10
  • 1
    @RajPatel Well, the linked post has some pointers for you, read it. – πάντα ῥεῖ Apr 24 '16 at 20:12

0 Answers0