1

I have a while loop that prints a prompt for an integer. I want to error check for when the user enters a char, like 'a'. However, when I type 'a', it prints "Enter the seed: Seed must be an integer value, please try again" forever.

int getSeed() {
    int scanned, seed;

    while (scanned == 0) {
       printf("Enter the seed: ");
       scanned = scanf("%d", &seed);
       if (scanned == 0) {
          printf("Seed must be an integer, try again\n");
       }
    }
    return seed;
}

How do I get this to print

Enter the seed: a Seed must be an integer, try again Enter the seed:

Thanks.

EDIT: Solved it, I added getchar(); after the scanf.

Arnold Hotz
  • 179
  • 1
  • 3
  • 8
  • 2
    Possible duplicate of [scanf not reading input](http://stackoverflow.com/questions/5289542/scanf-not-reading-input) – FiReTiTi Apr 02 '16 at 21:15
  • 1
    Your solution won't really solve it. Things will still go wrong if someone enters, for example "aa". If you want to read a line and then parse it, write code to do that. – David Schwartz Apr 02 '16 at 21:57

1 Answers1

0

scanf checks your input character and finds out that it does not match the conversion specifier, so it puts it back in the input stream.
Then in your while loop in your code reaches to scanf again, and the above process occurs again (since the a you've written in input stream is still there)

So a better solution would be reading it as a character (or string) and then converting that into an integer.

Ali Seyedi
  • 1,758
  • 1
  • 19
  • 24