I actually want to do this.
int i;
printf("enter choice:");
scanf ("%d", &i);
while (i>4 || i==0 || i is not an integer)
{ printf("invalid input. enter choice again between 1 to 4: ");
scanf ("%d", &i);}
pls help.
I actually want to do this.
int i;
printf("enter choice:");
scanf ("%d", &i);
while (i>4 || i==0 || i is not an integer)
{ printf("invalid input. enter choice again between 1 to 4: ");
scanf ("%d", &i);}
pls help.
The return value of scanf
gives you the number of items successfully assigned. In this case you have only one, the %d
, so the return value is either 1 for success or 0 for failure (i.e., the input was not a number) when input is available. If stdin
is closed or an input error occurs, scanf
will return EOF
(a defined constant with a value less than 0).
e.g
#include <stdio.h>
int main(){
int i=0, stat;
printf("enter choice:");
stat = scanf ("%d", &i);
while (i>4 || i<1 || stat !=1){
if(stat == EOF) return -1;
printf("invalid input. enter choice again between 1 to 4: ");
if(stat != 1)
scanf("%*[^\n]");//skip the bad input
stat = scanf ("%d", &i);
}
printf("your choice is %d\n", i);
return 0;
}
You can read the input as string and then convert it to an int :
char buf[256];
scanf("%s", buf); // will flush remaining bytes
int i = atoi(buf); // 0 on failure (strtol is safer)