-6

suppose I have a variable of integer type 'a'

now ill ask user to enter an input after he gave an input i want to check weather he entered an integer type or anything else

for the above question what should i have to do

v. vamsi
  • 11
  • 2
  • 6

3 Answers3

4

Read as a string, and try to convert to an integer using either std::stoi or strtol.

Or attempt to read as an integer, and check the status of std::cin afterwards (or while actually reading the input, streams can be used as boolean expressions), or what scanf returns.


Note how the methods to handle something like this differs between C++ and C? That's why it's important to use correct language tag when asking questions. Different languages has different solutions.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • @AshishAhuja The problem with that is that an integer is an integer. No matter what you write to it, it will always be an integer. The OP also says the the input to the variable comes from the user, therefore one can use the method of input to help detect if the user actually gave an integer, or to try and convert the input afterward to see if the input was an integer or something else. – Some programmer dude Feb 18 '16 at 06:49
1

If you're using scanf, check it's return values. This answer is for C.

On success, scanf returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.

So, a sample program:

#include <stdio.h>

int main()
{
    int a;
    if (scanf("%d", &a) == 1) {
        printf("Is integer\n");
    } else {
        printf("Not an integer.\n");
    }
    return 0;
}

Also see: Check if a value from scanf is a number?

Community
  • 1
  • 1
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
-1

C++ has an inbuilt operator called the typeid operator that you can use.

#include <typeinfo>

main(){
int a;
cin>>a;
if(typeid(a)==typeid(int))   //check whether your variable is integer type
//your code
}

Note: This works only for C++, not for C.

Akshay Gupta
  • 361
  • 1
  • 6
  • 17