I\'m trying to use safe practices in handling input with numbers only in C++, so I use a stringstream object as so:
#include
#include
A better way to do this conversion between datatypes would be to use boost::lexical_cast
.
Info and examples can be found at the Boost Site.
Below is an example of doing an int to string conversion and back (string to int) such as what you're doing in your program.
#include <string>
#include <boost/lexcal_cast.hpp>
int main(int argc, char *argv[])
{
int i = 42;
std::string s = boost::lexical_cast<std::string>(i);
int j = boost::lexical_cast<int>(s);
return 1;
}
You need to reset the state of the stringstream
. Generally, this involves two steps: clearing the buffer:
sstream.str("");
and resetting the error state flags:
sstream.clear();
If you don't clear the buffer, if you get an input like "123abc" then "abc" will still be in the stream when you try to read from it the next time.
You should also make sure to test the fail state of the stream (sstream.fail()
) to ensure that the extraction was successful. If you want to be sure that the user only entered an integer (i.e., you want to prevent the user from inputting, say, "123abc", then you should test to make sure sstream.eof()
is true.
cout << "First integer: ";
getline(cin, input);
sstream.str(input);
sstream >> first; // state of sstream may be eof
cout << "Second integer: ";
getline(cin, input);
sstream.str(input);
sstream.clear(); // clear eof state
sstream >> second; // input from sstream
Use sstream.clear();
after sstream >> first;
.