0

If you enter integer value the loop works just fine but if you enter some ASCII character or float type value the program goes into an infinite loop. Any fix for this issue? Technically, char is one type of int so this shouldn't be a problem.

#include <stdio.h>

int main(void)
{
  int num;

  scanf("%d",&num);
  while (num < 40)
  {
    printf("Number is small\n");
    scanf("%d",&num);
  }
  return 0;
}
Yun
  • 3,056
  • 6
  • 9
  • 28
arka
  • 418
  • 2
  • 9

1 Answers1

0

The function scanf will try to read a decimal integer from stdin. It uses the definition of a decimal integer from strtol:

The valid integer value consists of the following parts:

  • (optional) plus or minus sign
  • (optional) prefix (0) indicating octal base (applies only when the base is 8 or ​0​)
  • (optional) prefix (0x or 0X) indicating hexadecimal base (applies only when the base is 16 or ​0​)
  • a sequence of digits

In other words, scanf will try to interpret a sequence of characters on stdin as a decimal integer. It will not do a character to integer conversion based on the ASCII table.

The solution to your problem lies in checking the return value of scanf, which is:

Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.

So, check if scanf did not return 1. In this case, it has not read a decimal integer and num has not been assigned a value and should not be used.
In the given program, if num has never been assigned a value, its value is indeterminate. This could be a value <40, explaining the infinite loop as scanf repeatedly tries to read a non-integer from stdin, fails and leaves the non-integer on stdin as is. If num has been assigned a value before, it will still hold that value after a failed scanf call.

Yun
  • 3,056
  • 6
  • 9
  • 28