0

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.

M Ashraful A
  • 627
  • 6
  • 13

3 Answers3

1

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

Arkku
  • 41,011
  • 10
  • 62
  • 84
  • It is not true that *the return value is either 1 for success or 0 for failure*. It can be `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`. – Filipe Gonçalves Feb 25 '14 at 13:40
  • @FilipeGonçalves You are right, I edited the answer accordingly. – Arkku Feb 25 '14 at 13:41
  • Please write the full codes. i am not understanding. – M Ashraful A Feb 25 '14 at 13:51
  • @user3308618 If you do `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 */ }` – Arkku Feb 25 '14 at 13:53
  • can you pls tell me how to do it inside the while loop. I have done this, int i, result; printf("enter your choice:"); scanf ("%d", &i); result = scanf("%d", &i); while (i>4 || i==0 || result<1) { printf("invalid input\n enter your choice again: "); scanf ("%d", &i);} but the loop does not stop . :( – M Ashraful A Feb 25 '14 at 14:06
  • @user3308618 Copypaste the code inside a `while` -loop, or use only the `result = scanf(…)` in place of your current `scanf`s and put the `result` check into the condition of the loop? – Arkku Feb 25 '14 at 14:09
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;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
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)
Kiwi
  • 2,698
  • 16
  • 15