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).
EOF if the end of input is reached prematurely, or an I/O error happens. Subtle, yes, but I think it's worth mentioning it because it could lead the OP to have an infinite loop for not testing for EOF.result = scanf("%d", &i); where result is an int, then you can check if (result > 0) { /* a number was read */ } else { /* error or not a number */ }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;
}
scanf()returns the number of successful assignments made.