• Register
search
Log In

If you ever try to enter a digit inside a string or array 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 in the input. First we have to check if the input is a number or not. This article is only going to discuss how to check if the input is a number or a string.

Given an input by the user and we have to check whether the given input is an integer or just a string.

Example

Input-: 123
Output-: 123 is an integer
Input-: have a nice day
Output-: have a nice day is a string

Approach

  • Take the input by the user

  • Use the function isdigit() to check whether the input is numeric or string

  • Print the output

Algorithm

  • Declare a function to check if the input is number or string

  • Take input in our variable by the user

  • Call the function we just created to check 

  • Print output

#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
   for (int i = 0; i < str.length(); i++)
   if (isdigit(str[i]) == false)
      return false;
      return true;
}
int main() {
   string str = "have a nice day";
   if (check_number(str))
      cout<<str<< " is an integer"<<endl;
   else
      cout<<str<< " is a string"<<endl;
      string str1 = "1234";
   if (check_number(str1))
      cout<<str1<< " is an integer";
   else
      cout<<str1<< " is a string";
}

Output 

have a nice day is a string
1234 is an integer
posted Jun 19 in c++ 100 points