#include<stdio.h>
int main()
{
int n;
printf("write any integer:\n");
scanf("%d",&n);
}
I want to show error if input data by user will other than integer type. Then what may the conditions by which we can decide that entered data is integer type ?
if I write a character (let 'a') insted of integer type then how to identify that entered data is not integer and then show error that "You haven't entered integer".
I think It can be possible by using return type of scanf() or typecasting but I am not sure that it will work or not and how it will work?
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");
}
}