0

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.

jackscorrow
  • 621
  • 1
  • 6
  • 23
  • Sorry, I don't know the streams well enough to give an explanation, but maybe the answer to this question (declare ; as a whitespace character) helps as an alternative to writing your own parser: http://stackoverflow.com/questions/21764826/skipping-expected-characters-like-scanf-with-cin – mars Apr 15 '17 at 15:19
  • Doesn't explain why this fails but shows you how you can do it. Just replace `,` with `;` since you have semi-colon serarated data and not comma separated data. http://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c – NathanOliver Apr 15 '17 at 15:30

1 Answers1

1

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/

hiteshn97
  • 80
  • 2
  • 9