Scan and Loops

here is a piece of code that should loop again and again until the user enters a number from 0 to 15

        int input;

        do
        {

                printf("Enter a number => ");
                scanf("%d",&input);
                printf("\n %d \n",input);

        }
        while (!(input>0 && input <15));

However, if the user puts something like "gfggdf", this leads to the loop repeating itself, repeating itself again and again not asking the user for input ... the console looks like this

Enter a number =>
0
Enter a number =>
0
Enter a number =>
0
Enter a number =>
0
Enter a number =>
0
Enter a number =>
0
(looping indefinitely)

Looking through this book, I think I need to do something like this to prevent this from happening.

int input, error, status;
char skip_ch;

do
{
        error = 0;

        printf("Enter a number => ");
        status = scanf("%d",&input);
        printf("\n %d \n",input);

        if(status!=1)
        {
                error=1;
        }
        else if(input < 0 || input >15){
                error = 1;
        }

        do
        {
                scanf("%c",&skip_ch);
        }while(skip_ch != '\n');
}
while (error);

I understand that you need to check the status of scanf to make sure that this is valid input. What I don’t understand in the internal do-while loop. I feel like the book never explained to me why scanf needs to be called several times as if the scan buffer was full of garbage, and it somehow cleared it, just breaking it a million times.

- ?

+2
3

, ( "gfggdf" ) , scanf - , scanf () , , .

:

do {
        scanf("%c",&skip_ch);
}while(skip_ch != '\n');

( ), . , - : scanf("%*[^\n]");

, (, ) , - , , . , , , / , , . : , , . , .

+3

, scanf().

, scanf(), , - - .

fgets() sscanf() .

, , scanf() . ; getchar() :

int c;
while ((c = getchar()) != EOF && c != '\n')
    ;

'int c;' - "char" "unsigned char", char EOF.

+5

, scanf(), fgets().

Rate your condition (first code). 0 > 0- false. 0 < 15- true. false && true false. !false- true. That is why he is endlessly obsessed.

+1
source

All Articles