• Register
search
Log In

If you ever try to enter a digit inside a string variable, you will notice that it shows as if it is an i.e., digit. So, what if we are in the middle of a very big program and we don’t want integers inside the string. First we have to check if the string is a number or not. This article is only going to discuss how to check if the string is a number.

 

Approach

To check if the string is a numeric character or not, we have to use the function isdigit(). This function is declared in the “ctype.h” header file. So basically we must add the “ctype.h” header file. It returns an integer value, if the argument is a digit otherwise, it returns 0.

 

  • First we create a function isnumber to check whether the elements of the string are digit or not.

  • Then we define a string str.

  • Then we check if it is a number or not.

  • And in the end just put the output.

 

Example


#include<iostream>
#include<stdio.h>
#include<ctype.h>

using namespace std;

bool isnumber(string s)
{
    for (int i = 0; i < s.length(); i++)
    if (isdigit(s[i]) == false)
    return false;
     else
     {
         return true;
     }
     
}

int main() {
   string str = "5458";
   
   if (isnumber(str))
   cout << "integer";
   else
   {
       cout << "string";
   }
   
   
   return 0;
}

Output

integer

posted Jun 19 in c++ 100 points