Stringstream not working

Hi, I don't understand why the last row in the terminal is not 5. When I comment out "ss >> name" or use a new stringstream just for weight this works. Why? (Text in quotation in terminal is input.)

Terminal:
Input product 1: "Potato; 5 kg; 1 dollar;"
5 kg
0

Code:
string input, name;
double weight;
stringstream ss;

getline(is, input, ';');
ss.str(input);
ss >> name; //Works when I comment this out


getline(is, input, ';');
ss.str(input);
cout << input << endl;
ss >> weight;
cout << weight << endl;
Apparently eof is set on ss after the ss >> name.
You need to clear it before trying to read from it again:

 
    ss.clear();


BTW, you should use code tags when posting code and you should post a runnable program if possible.
Last edited on
Thank you!
Sorry, will do so in the future!
Why not simply:

1
2
3
4
5
6
7
8
9
10
11
	std::string input, name;

	std::getline(is, input, ';');
	std::getline(is, input, ';');

	std::stringstream ss(input);
	double weight {};

	std::cout << input << '\n';
	ss >> weight;
	std::cout << weight << '\n';


stringstream works similar to file stream and console stream - except uses a string for data instead of file or console. So the open modes, and stream state etc are similar to that for files/console etc.
Last edited on
Topic archived. No new replies allowed.