jackscorrow
jackscorrow

Reputation: 702

Proper usage of operator >> subsequent times on same input stream

I'm writing some code in order to read some parameters values from a file.

I know that if, let's say, I have a stringstream object stream created from the string "10" I can initialize a numeric variable defined as int var1; just by typing:

stream >> var1;

What if now my stringstream object is created from the string "10;3;4.5;3.2;" and I have four variables declared as follows:

int var1;
int var2;
double var3;
double var4;

Can I write something like this:

stream >> var1;
stream >> var2;
stream >> var3;
stream >> var4;

in order to initialize all the four variables from this stream? Or my only option is to implement a simple parser to extract each value one at a time and then store that value into each one of them?

Well, in fact I tried it and it doesn't work. var1 gets initialized correctly but the other variables are all initialized to 0.

Can you explain why this doesn't work? Thank you in advance for your help.

Upvotes: 0

Views: 49

Answers (1)

hiteshn97
hiteshn97

Reputation: 90

Working with streams is a bit tricky but also interesting at the same time. To parse this using stringstreams, just modify the code a little to take into account the semicolon. Here is how:

//  stream = "10;3;4.5;3.2;"
stream >> var1;
//  stream = ";3;4.5;3.2;"
//  now if you will input stream >> var2,
//  will extract till the next integer value exists.
//  But here, since character ';' and not an integer, it won't pass any value to var2.
//  To correct it, add this line to take are of the ';' :
char ch;
stream >> ch;
stream >> var2 >> ch;
stream >> var3 >> ch;
stream >> var4;

To understand this, you need to get a better understanding of how the stream extracts input from the input buffer. I've tried to explain it step by step.

For a better understanding on this topic refer to this: http://www.learncpp.com/cpp-tutorial/184-stream-classes-for-strings/

Upvotes: 1

Related Questions