Program to find out the data type of user input in C++


In this problem, we are given input from the user. Our task is to create a program to find out the data type of user input in C++.

Problem Description − We will take input from the user and check the data type of the input value.

Let’s take an example to understand the problem,

Example 1:

Input − 34

Output − It is an integer

Example 2:

Input − tutorialspoint

Output − It is a string

Solution Approach:

We will check if the input string is a number or not a number.

If it is a number, we will check if it is an integer or a float value.

If it is not a number, we will check if it is a string.

Example

 Live Demo

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
   char input[50] = "";
   double temp;
   int intVal;
   char stringVal[50] = "";
   double val = 1e-12;
   fgets(input, 100, stdin);
   if (sscanf(input, "%lf", &temp) == 1) {
      intVal = (int)temp;
      if (fabs(temp - intVal) / temp > val)
         printf("The input is a floating point\n");
      else
         printf("The input is an integer\n");
   }
   else if (sscanf(input, "%s", stringVal) == 1)
      printf("The input is a string\n");
   else
      printf("input not recognized\n");
}

Input:

452

Output:

The input is an integer

Updated on: 01-Oct-2020

642 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements