Program to check if input is an integer or a string


Write a function to check whether a given input is an integer or a string.

Definition of an integer :

Every element should be a valid digit, i.e '0-9'.

Definition of a string :

Any one element should be an invalid digit, i.e any symbol other than '0-9'.


Input : 127
Output : Integer
Explanation : All digits are in the range '0-9'.

Input : 199.7
Output : String
Explanation : A dot is present. 

Input : 122B
Output : String
Explanation : A alphabet is present.

The idea is to use isdigit() in C++.
Below is the C++ implementation :

// CPP program to check if a given string
// is a valid integer
#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 = "6790";

    // 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
        cout << "String";



This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at to report any issue with the above content.

Recommended Posts:

2.7 Average Difficulty : 2.7/5.0
Based on 4 vote(s)