-2

I'm trying to write a small function that will get a number. The function should be idiot-proof so it would give warnings if ie. someone entered a character instead.

I wrote a function like the one below, but if I enter a non-int the program gives me an infinite loop, constantly repeating the printf "Not a valid number" so I never get a chance to do the correct input.

The code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    for (int ret = 0; ret < 1;)
    {
        int num;

        printf("\n Please input a number: ");
        ret = scanf ("%d", &num);
        if (ret < 1)
            printf ("\nNot a valid number!");
        else
            printf("\nYou input %d", num);
    }
    return 0;
}

How to fix it?

Cœur
  • 37,241
  • 25
  • 195
  • 267
aln447
  • 981
  • 2
  • 15
  • 44

2 Answers2

2

Replace this line if (y = 0) with this if (y == 0).

webpersistence
  • 894
  • 3
  • 12
  • 29
  • This solution fixes a bug but not the problem. The problem is that all the scanf-s after the first one will return immediately (without blocking on new input) if the user inputs texts instead of a number. That's why the question is about an infinite number of printouts not simply an incorrect printout. – GroovyDotCom Jan 01 '15 at 17:47
0

Note the line below with the comment about eating the input buffer. Since your scanf didn't find what it is looking for in the input buffer, the wrong input just stays there and fails forever unless you do something to "eat" it.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("Hello world!\n");
    while ('A')
    {
        int x, y;
        printf("\n x: ");

        y = scanf ("%d", &x);
        printf("\nx = %d", x);
        if (y < 1)
        { // eat the input buffer so we can try again
            while ( getchar() != '\n' );
            printf ("\nWRONG!");
        }
    }

    return 0;
}
GroovyDotCom
  • 1,304
  • 2
  • 15
  • 29
  • You edit the question to change the `while` into a `for`, but your answer uses a `while`: could you please have it consistent between the two posts? – Cœur Feb 18 '19 at 15:25