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

C++Server Side ProgrammingProgramming

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

  • Input the data.
  • Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.
  • Print the resultant output.

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

 Live Demo

#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
raja
Published on 18-Oct-2019 11:47:44
Advertisements