Problem:
When working with user input, you may encounter strings that contain a mix of words and numbers. If you want to isolate only the words, you need a method to distinguish them from numbers.
Solution:
One approach to verifying if a string represents an integer is to employ the strtol() function. To simplify its usage, you can incorporate it into a custom function:
<code class="cpp">inline bool isInteger(const std::string & s) { if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false; char * p; strtol(s.c_str(), &p, 10); return (*p == 0); }</code>
Explanation:
strtol() parses a string as a numerical value, stopping at the first non-numerical character. By supplying a pointer to a character variable (p), it indicates the position of the first invalid character. If p points to the end of the string, all characters were successfully converted, indicating that the string is an integer.
Usage:
Within your main function, you can integrate this function as follows:
<code class="cpp">int main () { stringstream ss (stringstream::in | stringstream::out); string word; string str; getline(cin,str); ss<<str; while(ss>>word) { if(isInteger(word)) continue; cout<<word<<endl; } }</code>
This will output words that are not integers while ignoring numerical inputs.
The above is the detailed content of How to Determine if a C String Represents an Integer?. For more information, please follow other related articles on the PHP Chinese website!