"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Check If a C++ String Represents an Integer?

How to Check If a C++ String Represents an Integer?

Published on 2024-11-12
Browse:790

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:

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);
}
  • Overview: The function checks if the provided string s represents an integer.
  • Empty Strings: It first checks if the string is empty.
  • Leading Symbols: It also checks for leading non-digit characters, such as ' ' or '-', and returns false if they are not present (indicating a non-integer).
  • strtol Conversion: The function utilizes the strtol function to perform the conversion. If strtol encounters a non-digit character, it assigns the address of that character to the pointer p.
  • Result Evaluation: If p is not pointing to the end of the string (represented by the '\0' character), it means strtol encountered a non-digit character. In this case, the function returns false, indicating that s is not an integer.

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.

Latest tutorial More>

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