scanf ignoring, infinite loop

后端 未结 6 1020
遥遥无期
遥遥无期 2020-11-27 22:54
int flag = 0;
int price = 0;
while (flag==0)
{
    printf(\"\\nEnter Product price: \");
    scanf(\"%d\",&price);
    if (price==0) 
        printf(\"input not          


        
6条回答
  •  温柔的废话
    2020-11-27 23:08

    The %d format is for decimals. When scanf fails (something other a decimal is entered) the character that caused it to fail will remain as the input.

    Example.

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

    So no conversion occurs.

    The scanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure

    7.19.6. The scanf function - JTC1/SC22/WG14 - C

    So you should note that scanf returns its own form of notice for success

    int scanf(char *format)
    

    so you could have also did the following

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

    Also keep in the back of your head to try to stay away from scanf. scanf or scan formatted should not be used for interactive user input. See the C FAQ 12.20

提交回复
热议问题