Home > Article > Backend Development > How to Check If a C String Represents an Integer?
Checking If a C String is an Integer
In certain situations, such as when processing user input, it may be necessary to differentiate between strings that represent integers and those that do not. Luckily, there are several ways to achieve this task in C .
One approach is to leverage the C function strtol, which converts a string representation of an integer to an integer value. To use strtol, you can write a simple function that encapsulates the conversion process:
<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>
The above is the detailed content of How to Check If a C String Represents an Integer?. For more information, please follow other related articles on the PHP Chinese website!