• Register

 

In a variable, we can store some values like integers, characters and et cetera. We can identify them by their data types in the program. But how we are gonna find out if the input is an integer or not. We are going to write a program for finding out in this article. 

We can use this little in many ways like in a particular program we want to take input as an integer from the user. For finding out whether the input given by a user is int or anything else, we can use this program.

 

Explanation

 

Before going further we should know the definition of integers. 

Every element with a valid digit, i.e., 0-9, is known as integers.

 

Example

 

Input: 5846

Output: integer

 

input : 561.145

Output: not integer

Since it contains a dot it is not an integer according to c++.

 

Solution

 

isdigit() and is_numeric() functions will be used for this particular program.

#include <iostream> 
using namespace std; 
  
// Returns true if s is a number else false 
bool isNumber(string s) 
{ 
    for (int i = 0; i < s.length(); i++) 
        if (isdigit(s[i]) == false) 
            return false; 
  
    return true; 
} 
  
// Driver code 
int main() 
{ 
    // Saving the input in a string 
    string str = "679b0"; 
  
    // Function returns 1 if all elements 
    // are in range '0-9' 
    if (isNumber(str)) 
        cout << "Integer"; 
  
    // Function returns 0 if the input is 
    // not an integer 
    else
        cout << "Not Integer"; 
} 

The output of this program is Output: Not Integer

If you have any doubt you can ask in the comment section.

posted May 22 in c++ 140 points