How do you use istringstream?

from a file the data holds:
Bob 20 M
Billy S Fred 12 M
Joanna Mil 26 F

Name >> age >> gender

how would you use istringstream to assign each data into the types?

so far i have...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main(void)
{
    string line;
    ifstream infile;
	string name;
	int age;
	char gender;
    istringstream instream;
    infile.open("student.txt");
    
    while(getline(infile, line)) 
    {
        instream.clear();

		instream >> name >> age >> gender >> email >> uid;
		cout << "name: " << name << endl;
		cout << "age: " << age;
		cout << "gender: " << gender;
    }


thank you in advance.
Looks good... you just forget to give your std::istringstream the line.

Replace:

instream.clear();

with

instream.str(line);

http://cplusplus.com/reference/sstream/basic_istringstream/str/

Minor notes:

1)

1
2
3
4
5
int main(void)

// should be

int main() // because this is C++, not C 


2) you should be consistent with your indentation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    string line;
    ifstream infile;
    string name;
    int age;
    char gender;
    istringstream instream;
    infile.open("student.txt");
    
    while(getline(infile, line)) 
    {
        instream.clear();

        instream >> name >> age >> gender >> email >> uid;
        cout << "name: " << name << endl;
        cout << "age: " << age;
        cout << "gender: " << gender;
    }
catfish3 thanks
but it doesnt seem to work when the name contains more than one word.
the age becomes 0 and stops working ?
Tokens are separated by space.
So if name is of the form "Albert McGee", it is separated into "Albert" and "McGee".

I can think of two easy ways to deal with this:

1) make it so that a name is like "Albert_McGee", "Julia_Foxy_Richards"

2) establish how many different tokens make up a name (e.g. 2) then do something like:

1
2
3
4
string name, surname, full_name;

instream >> name >> surname;
full_name = name + surname;
"Comma separated value" formats are popular, because they make it easier to identify multi-word fields. http://en.wikipedia.org/wiki/Comma-separated_values

Just like Catfish3 option (1), CSV requires changes into the file before reading it.

The other option is to trust that each line contains three "fields": a multi-word, a number, and a character. Read a line. Take the last char as gender. Convert the second to last word into number. Combine the remaining words into name.

String has rfind(), so you can find second to last "whitespace" easily.
Topic archived. No new replies allowed.