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.

5
  • 1
    Hint: scanf() returns the number of successful assignments made. Commented Feb 25, 2014 at 13:35
  • Read Scanf won't execute for second time I think it will help you. Commented Feb 25, 2014 at 13:40
  • 1
    This might be useful link Commented Feb 25, 2014 at 13:41
  • Please format your code. Commented Feb 25, 2014 at 13:43
  • 1
    i is always a number. It is an int. Commented Feb 25, 2014 at 13:44

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

6 Comments

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.
@FilipeGonçalves You are right, I edited the answer accordingly.
Please write the full codes. i am not understanding.
@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 */ }
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 . :(
|
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;
}

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.