Home >Backend Development >C++ >How to Check If a C String Represents an Integer?

How to Check If a C String Represents an Integer?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 21:32:02457browse

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>
  • 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 '

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn