When I use getline, I would input a bunch of strings or numbers, but I only want the while loop to output the “word” if it is not a number.
So is there any way to check if “word” is a number or not? I know I could use atoi() for
C-strings but how about for strings of the string class?
int main () {
stringstream ss (stringstream::in | stringstream::out);
string word;
string str;
getline(cin,str);
ss<<str;
while(ss>>word)
{
//if( )
cout<<word<<endl;
}
}
Another version…
Use
strtol, wrapping it inside a simple function to hide its complexity :Why
strtol?As far as I love C++, sometimes the C API is the best answer as far as I am concerned:
How does it work ?
strtolseems quite raw at first glance, so an explanation will make the code simpler to read :strtolwill parse the string, stopping at the first character that cannot be considered part of an integer. If you providep(as I did above), it setspright at this first non-integer character.My reasoning is that if
pis not set to the end of the string (the 0 character), then there is a non-integer character in the strings, meaningsis not a correct integer.The first tests are there to eliminate corner cases (leading spaces, empty string, etc.).
This function should be, of course, customized to your needs (are leading spaces an error? etc.).
Sources :
See the description of
strtolat: http://en.cppreference.com/w/cpp/string/byte/strtol.See, too, the description of
strtol‘s sister functions (strtod,strtoul, etc.).