parsing command line
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!
string cmd_line = " ";
string cmd = " ";
int find_this_number = 0;
// Read in what-ever the user typed in...
// Get the first word in the string
getline(ss, cmd, ' ');
// Check whether the user typed in an integer
if ((scmd >> find_this_number).fail() )
cout << "oops, you typed: " << cmd << endl;
cout << "The number is: " << find_this_number << endl;
Then you're just going to have to check if all the characters in that stream are integers aren't you?
There's http://www.cplusplus.com/reference/std/locale/isdigit/ or just do what you're doing but in a loop for each character.
Or you could use std::string.find_first_not_of() to check that the entire string doesn't contain any letters, or whatever else is invalid.
Also note: Most people consider the "command line" to be the variables passed to your program when you start it, not the use of an input stream.
Easier and better idea. Outshow me, will ya? *gets the mallet* o3o
Originally Posted by jimblumberg