M
M
Max2020-04-21 23:36:10
C++ / C#
Max, 2020-04-21 23:36:10

Why does the loop run indefinitely when a non-numeric value is entered?

#include <stdio.h>

int main()
{
    float firstNum;
    while (scanf("%f", &firstNum) == 0) {
      printf("Enter a NUMBER: ");
  }

    return 0;
}

It is necessary that when a non-numeric value is entered, the loop works and re-requests the value, but when a letter is entered, the loop runs endlessly and a message is simply displayed from printf without the possibility of re-entering data. What is the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-04-22
@max10110

What is the problem?

That the data read by scanf is a stream. If the format (in your case %f) cannot retrieve the data from the stream, it stays there.
To dump data that is unreadable you can use scanf("%*[^\n]");:
while (scanf("%f", &firstNum) == 0) {
      printf("Enter a NUMBER: ");
      scanf("%*[^\n]");
  }

This construct reads the current line up to the end-of-line character into a void.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question