Hi all, I'm trying to use safe practices in handling input with numbers only in C++, so I use a stringstream object as so:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int first, second;
string input;
stringstream sstream;
cout << "First integer: ";
getline(cin, input);
sstream.str(input);
sstream >> first;
cout << first << endl; //display user input in integers
cout << "Second integer: ";
getline(cin, input);
sstream.str(input);
sstream >> second;
cout << second << endl; //display user input in integers
getline(cin, input); //pause program
return 0;
}
However, the second time around it seems to give the variable 'second' an arbitrary value. This is the output:
First integer: 1
1
Second integer: 2
2293592
If I declare two stringstream objects and use them respectively for both variables it seems to work fine. Does this mean that I cannot re-use a stringstream object in the way I'm trying to do? In my real program I intend to handle much more than two input values from the user, so I just want to make sure if there's another way instead of making multiple stringstream objects. I doubt it's of great relevance but I'm on Windows XP and I'm using MinGW as my compiler.
I greatly appreciate any help.