C++ Program to check if input is an integer or a string


Given with an input by the user and the task is to check whether the given input is an integer or a string.

Integer can be any combination of digits between 0 -9 and string can be any combination excluding 0 – 9.

Example

Input-: 123
Output-: 123 is an integer
Input-: Tutorials Point
Output-: Tutorials Point is a string

Approach used below is as follows

Algorithm

Start
Step 1->declare function to check if number or string
   bool check_number(string str)
   Loop For int i = 0 and i < str.length() and i++
      If (isdigit(str[i]) == false)
         return false
      End
   End
   return true
step 2->Int main()
   set string str = "sunidhi"
      IF (check_number(str))
         Print " is an integer"
      End
      Else
         Print " is a string"
      End
      Set string str1 = "1234"
         IF (check_number(str1))
            Print " is an integer"
         End
         Else
            Print " is a string"
         End
Stop

Example

#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 = "sunidhi";
   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

sunidhi is a string
1234 is an integer

Updated on: 02-Nov-2023

35K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements