• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
November 04, 2022 |28.8K Views
C++ Program to check if Input is an integer or a string
  Share  2 Likes
Description
Discussion

In this video, we will see C++ Program to check if the Input is an integer or a string.

An integer can be defined as every element that should be a valid digit, from '0-9', and strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’.

Examples:

Input: 128
Output: Integer
Explanation: All digits are in the range of 0-9.

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

Input: 132GFG
Output: String
Explanation: A alphabet is present, so it is a string.

Here we see two methods for checking if the Input is an integer or a string:


Using isdigit(c):

The isdigit(c) is a function in C++ that can be used to check if the passed character is a digit or not. It returns a non-zero value if it is a digit else it returns 0. For example, it returns a non-zero value for ‘0’ to ‘9’ and zero for others.
Step 1: Save the input as a string.
Step 2: Use the isdigit() function to check for each character of the string whether it is a digit or not.
Step 3: If the whole string consists of digits then it is an integer, otherwise it is a string.

Time complexity: O(n)
Space Complexity: 0(1)


Using user-defined():
Step 1: Take input as a string.
Step 2: In the function check the condition for each character of the string whether it is a digit or not.
Step 3: For integers, every element should be a digit i.e 0-9
Step 4: For string, any one element of the input string should not be a digit.
Time complexity: O(n)
Space Complexity: 0(1)
 

Read More