Hi there,
I have done a fair amount of research in order to figure out how to parse a command line for, say, and integer. The code below almost works, except when the user types in, for example, "4s". The result is that find_this_number gets assigned 4, whereas I would prefer to reject the input "4s" because the string does not represent an integer.
Some people have recommended using the boost library, but I would like to know if there is a way to do this using either strict C or the STL libraries only. Can you please help? Thanks!
Aaron
insert
Code:
string cmd_line = " ";
string cmd = " ";
int find_this_number = 0;
// Read in what-ever the user typed in...
getline(cin, cmd_line);
istringstream ss(cmd_line);
// Get the first word in the string
getline(ss, cmd, ' ');
// Check whether the user typed in an integer
stringstream scmd(cmd);
if ((scmd >> find_this_number).fail() )
{
cin.clear();
cout << "oops, you typed: " << cmd << endl;
}
else
{
cout << "The number is: " << find_this_number << endl;
}