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:
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);
}
This function provides a reliable way to determine if a given string can be parsed as an integer. By incorporating it into your code, you can handle strings representing integers and non-integers appropriately.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3