Home > front end >  C - Infinite loop after read a large decimal input from integer var
C - Infinite loop after read a large decimal input from integer var

Time:06-16

I am new to C. I am writing this do while loop but when I accidentally enter a decimal/double to the input, it will enter a infinite loop. Would you please correct me? Thank you!

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
    int items;
   do {
        printf("Input item quantity: ");
        scanf("%d", &items);
        if (items < 1 || items > 10)
            printf("ERROR: It must between 1 - 10.\n");
    } while (items < 1 || items > 10);
    return 0;
    
}

If I try to input 300.5, the output will become a loop

```
Input item quantity: ERROR: It must between 1 - 10.
Input item quantity: ERROR: It must between 1 - 10.
Input item quantity: ERROR: It must between 1 - 10.
```

CodePudding user response:

When scanf sees “.”, it stops scanning and leaves the “.” in the input stream. Your program receives 300 in items, for which it prints the message and loops. The next iteration of the loop calls scanf again. The “.” is still in the input stream, so scanf stops without changing items and returns zero to indicate it assigned zero items. Your program does not check the return result of scanf, so it fails to see this. It only checks the value of items, which has not changed.

Change the program to check the return value of scanf and to handle issues if the return value is not one, meaning that one item was assigned. To continue processing, you may need to use getchar or another input routine to read characters from the input until a new-line character is seen, marking the end of the line that the user typed.

Also, even if one item is assigned, you may wish to read the rest of the input line to see if the user entered any other notable characters, such as anything other than spaces. If they did, you may wish to report an error even if the assigned value is within range.

CodePudding user response:

To answer your comment about escaping the loop you might check out the following link:

Clear scanf Buffer

Using that advice, I added a catch-all integer variable to your code.

int items, catchall; /* Added variable "catchall" */

Then, I enclosed your error message and added the code similar to the link to your program.

    if (items < 1 || items > 10)
    {
        printf("ERROR: It must between 1 - 10.\n");
        while ((catchall = getchar()) != '\n' && catchall != EOF) /* Clean up the buffer */
        {}
    }

That effectively clears out the "scanf" buffer so that your program can get out of the endless loop, and I did not see any undesired knock-on effects.

Hope that helps.

Regards.

  •  Tags:  
  • c
  • Related