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
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
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.
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?
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.