deleting unprocessed chars on stdin

Using Visual C++, I created this this function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int GetNum() {
   char buffer[3];
   size_t size_read;

   int i = 0;
   printf("Enter a value (number) for the node between 1-99:\n");
   _cgets_s(buffer, _countof(buffer), &size_read);
   i = atoi(buffer);
   if ( i == 0 || (i != 0 && (i < 1 || i > 99 ) ) ) {
      printf("Bad input, using 0.\n");
      return 0;
   }
   else
      return i;
}


Often, there seems to be an unexpected character (or characters) hanging out in stdin, such that, when the function is called to get a number, the program does not wait for the user to enter a number -- the program finds its input waiting for it.

I searched on the web for a solution to this and found this suggestion:

while ((c = getchar()) != '\n' && c != EOF);

But that seems to put the program in an infinite loop.

So, looking for any suggestions on how to clear the input stream so that there are no lingering chars.

Last edited on
End of stream is -1, so you should check for that too.
@kbw
EOF == -1

@dschwart
The problem is that you are not getting input properly -- so your input routines and the input data are not properly synchronized.

As I have said (many, many times): the user will always press Enter at the end of every input.

That said, every time you ask the user for something and scanf() it, you should then clear all input to the next newline.

Thereafter you can expect the next input to work properly.

Hope this helps.
OK, none of your responses enabled me to get _cgets_s to work. Thanks for nothing (juuuust kidding). But the reference to scanf made me think...Hmm, so, I replaced _cgets_s with scanf.
And viola.
Problem gone.
So, from this I leaned a very, very important lesson: _cgets_s bad, scanf good.
Life is so simple.
Thanks.
Last edited on
Topic archived. No new replies allowed.