I just wrote this code a few days ago for determining if the user input is an integer or not. You'll have to change the size of buf
in case the input gets too large or buf
will overflow.
Also as Steve Summit said,
Handling bad input is an important but surprisingly hard problem. First you might want to think about which, if any, of these inputs you want to count as wrong: 1, -1, 01, 000001, 1., 1.1, 1x, 1e, 1e1, 100000000000000000, 1000000000000000000000000000. You might also have to think about (a) leading/trailing whitespace, and (b) leading/trailing \n
In case of the code below, inputs like
1 1
, 1.1
, .1
, 1e1
, 1x
, a
are considered Not Int
while inputs like 100
, 100
, 100
, -10
are considered Int
#include<stdio.h>
#include<ctype.h> //using ctype.h as suggested by Steve Summit
int check(char *buf){ //for checking trailing whitespace characters
for(int i=0;buf[i]!='\0';i++){
if(!isspace(buf[i])){
return 0;
}
}
return 1;
}
int main(){
int x;
char buf[10]; //change buf to appropriate length based on the input or it may overflow
scanf("%d",&x);
if(scanf("%[^\n]",buf)==0||check(buf)){
printf("Int");
}
else{
printf("Not Int");
}
}