Hi all.

Just a quick question for anyone who may be able to ehelp.

If a user is to enter a choice and i use scanf to read it in.
When that choice is a character that is entered, if the user enters either a character that is not that which is allowed or they enter a number the loop will work fine and it will refresh and get the user to enter it again.
However, i have set up some do while loops when the user is to enter a number and i can set up a do while that will set a range that the number has to be in and if a number outside this is entered the loop works fine but if a character is entered it starts to flicker and freezes up.

Does anyone know how i can overcome this. It is not a huge issue as i have finished my assignments but it would be nice to sort out this last bug! I guess it is some form of discrimination? Any help would be very appreciated.

Thanks everyone :)

Recommended Answers

All 4 Replies

Yes, use fgets() to read the whole line, then sscanf() to parse it.

If the line is rubbish, then you've already cleaned up the input stream to have another go.

scanf fails if it can't convert the incoming stream into a valid number, and it doesn't extract the bad characters. So unless you extract them yourself you'll get an infinite loop as scanf continues to fail on the same stuff.

// Unsafe; risks an infinite loop
while (scanf("%d", &x) != 1) {
  printf("Invalid number. Please try again: ");
  fflush(stdout);
}
// Safe; clearing the stream each time
while (scanf("%d", &x) != 1) {
  int ch;

  printf("Invalid number. Please try again: ");
  fflush(stdout);

  // Clear the stream state
  clearerr(stdin);

  // "Flush" the stream
  while ((ch = getc(stdin)) != '\n' && ch != EOF)
    ;
}

Hi thanks for the info. Just not too sure what "fflush" and "clearerr" are?

Would you mind just explaining what they are doing in that piece of code. These are a couple of commands i haven't used before.
Thanks :)

>Just not too sure what "fflush" and "clearerr" are?
That's what reference manuals are for.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.