[C language ] Scanf character input (%d): infinite loop error


When completing tasks from the seventh chapter, for the first time I encountered a “pinched cycle”. Let’s say the user enters the character q into a field (don’t do this unless you have the ability to interrupt the program):

#include <stdio.h>
int main (void)
{
int n;
scanf("%d", &n);
while (n > 0)
{
    printf("Enter 0 to quit:\n");
    scanf("%d", &n);
}
getchar();
return 0;
}

The program will get stuck in an infinite loop when entering any character value. Why so?

The fact is that if the type of a variable in scanf does not match, the program does not read it; but it does not remove from the buffer. As a result, the cycle returns to it endlessly.

Why is the symbol not removed? This is necessary so that if you read a sequence, for example, scanf with input %d%f and on input you have 123Vasia — scanf does not overwrite the V character when it reaches it.

To avoid such errors, it is necessary to clear the buffer, for example, like this:

#include <stdio.h>
int main (void)
{
int n;
scanf("%d", &n);
while (n > 0)
{
    while (getchar() != '\n')
        continue;
    printf("Enter 0 to quit:\n");
    scanf("%d", &n);
}
getchar();
return 0;
}

Write your comments!


This entry was posted in C language (en). Bookmark the permalink.

One Response to [C language ] Scanf character input (%d): infinite loop error

  1. Luis says:

    I love you

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.