Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

istringstream - how to do this?

Tags:

c++

file-io

I have a file:

a 0 0
b 1 1
c 3 4
d 5 6

Using istringstream, I need to get a, then b, then c, etc. But I don't know how to do it because there are no good examples online or in my book.

Code so far:

ifstream file;
file.open("file.txt");
string line;

getline(file,line);
istringstream iss(line);
iss >> id;

getline(file,line);
iss >> id;

This prints "a" for id both times. I don't know how to use istringstream obviously and I HAVE to use istringstream. Please help!

like image 602
Aaron McKellar Avatar asked Feb 24 '10 05:02

Aaron McKellar


2 Answers

ifstream file;
file.open("file.txt");
string line;

getline(file,line);
istringstream iss(line);
iss >> id;

getline(file,line);
istringstream iss2(line);
iss2 >> id;

getline(file,line);
iss.str(line);
iss >> id;

istringstream copies the string that you give it. It can't see changes to line. Either construct a new string stream, or force it to take a new copy of the string.

like image 160
ephemient Avatar answered Sep 28 '22 01:09

ephemient


You could also do this by having two while loops :-/ .

while ( getline(file, line))
{
    istringstream iss(line);

    while(iss >> term)
    {
        cout << term<< endl; // typing all the terms
    }
}
like image 42
Ahmad Khwileh Avatar answered Sep 28 '22 00:09

Ahmad Khwileh