Home > Backend Development > C++ > How to check if input is an integer using C/C++?

How to check if input is an integer using C/C++?

PHPz
Release: 2023-09-07 11:21:15
forward
1489 people have browsed it

How to check if input is an integer using C/C++?

Here we will see how to check if the given input is an integer string or a normal string. The integer string will contain all characters in the range 0-9. The solution is very simple, we will check each character one by one and then check if it is a number. If it is a number, it points to the next character, otherwise it returns a false value.

Example

#include <iostream>
using namespace std;
bool isNumeric(string str) {
   for (int i = 0; i < str.length(); i++)
      if (isdigit(str[i]) == false)
      return false; //when one non numeric value is found, return false
   return true;
}
int main() {
   string str;
   cout << "Enter a string: ";
   cin >> str;
   if (isNumeric(str))
      cout << "This is a Number" << endl;
   else
      cout << "This is not a number";
}
Copy after login

Output

Enter a string: 5687
This is a Number
Copy after login

Output

Enter a string: 584asS
This is not a number
Copy after login

The above is the detailed content of How to check if input is an integer using C/C++?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
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