Home > Backend Development > C++ > How to Determine if a C String Represents an Integer?

How to Determine if a C String Represents an Integer?

DDD
Release: 2024-11-07 04:17:02
Original
374 people have browsed it

How to Determine if a C   String Represents an Integer?

Determining if a C String Represents an Integer

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])) &amp;&amp; (s[0] != '-') &amp;&amp; (s[0] != '+'))) return false;

   char * p;
   strtol(s.c_str(), &amp;p, 10);

   return (*p == 0);
}</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template