Scanf ignore, infinite loop

int flag = 0;
int price = 0;
while (flag==0)
{
    printf("\nEnter Product price: ");
    scanf("%d",&price);
    if (price==0) 
        printf("input not valid\n"); 
    else 
        flag=1;
}

When I enter a real number, the loop ends as expected. But if I introduce something that is not a number, for example hello, then the code goes into an infinite loop. He just prints Enter Product price:and input not valid. But I do not need to enter a new number. Why is this?

+3
source share
6 answers

When you enter something that is not a number, it scanfwill fail and leave these characters in the input. Therefore, if you enter hello, scanf will see h, reject it as invalid for the decimal number and leave it in the input. Next time through the cycle, scanfhe will see again h, so that he will simply continue the cycle forever.

fgets, sscanf. , sscanf , . fgets .

- :

char buffer[STRING_SIZE];
...
while(...) {
    ...
    fgets(buffer, STRING_SIZE, stdin);
    if ( sscanf(buffer, "%d", &price) == 1 )
        break;   // sscanf succeeded, end the loop
    ...
}

getchar, , \n , - (, , , ).

sscanf. , , , , . 1 , sscanf 1, .

+4

% d . scanf (- ), , , .

.

    int va;
    scanf("%d",&va);
    printf("Val %d 1 \n", val);

    scanf("%d",&va);
    printf("Val %d 2 \n", val);
    return 0;

, .

scanf EOF, . scanf , , , ,

7.19.6. scanf - JTC1/SC22/WG14 - C

, , scanf

int scanf(char *format)

do {
        printf("Enter Product \n");
}
while (scanf("%d", &sale.m_price) == 1);

if(scanf("%d", &sale.m_price) == 0)
        PrintWrongInput();

, scanf. scanf . . C FAQ 12.20

+3

'\n' ( ), scanf (becouse\n ), scanf \n , ..

, '\n' getchar() scanf.

+1

"", , , "\n", - scanf("%d", ...) , .

, x 0, scanf ( ) EOF, x 0, . , , .

+1

, scanf() , . scanf() . stdin.

if (! scanf ( "% d", & sale.m_price))  fflush (STDIN);

0

: , , , scanf().

  • , - , scanf() , , scanf() , , , , scans() scanf().
  • -, , , , scanf().

scanf("%d", &price) , scanf() integer , , scanf() , , , , scanf() , .

scanf(), , , , , enter, , getchar() , enter , , enter , , , newline character . , scanf() integer , \n , getchar() will read it, but since you don't need it, it's safe to drop it:

#include <stdio.h>

int main(void)
{
    int flag = 0;
    int price = 0;
    int status = 0;
    while (flag == 0 && status != 1)
    {
        printf("\nEnter Product price: ");
        status = scanf("%d", &price);
        getchar();
        if (price == 0) 
            printf("input not valid\n"); 
        else 
            flag = 1;
    }   

    return 0;
}
0
source

All Articles