0

I'm using while(getchar()!= '\n'); to clear the buffer if the user inputs more than one character.

If more than one character is entered the program doesn't get stuck. But if one character is entered the program waits for me to hit enter to continue. How can i get it to continue even if only one character is entered? Thanks for any help provided!

Mark
  • 1
  • 1
  • 6
    It is always good to post your code snippet here rather than explaining theoretically.. – µtex Nov 21 '14 at 21:04

1 Answers1

0

You can check the keyboard buffer before committing to a read

while (kbhit()) getch();
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • 1
    `kbhit()` isn't standard and may not be available. – Dmitri Nov 21 '14 at 21:14
  • This function is sort of "illegal". – µtex Nov 21 '14 at 21:16
  • I was going to add that it's no use checking after the desired input, because the code execution could be ahead of the user's typing, so it should be just before the next user input. But the same applies. OP originally commented that his one line posted was enough, but it isn't. In any case, the GIGO rule applies. – Weather Vane Nov 21 '14 at 21:20
  • A previous SO answer using `kbhit()` was given +4 and tick, but I get a down vote. http://stackoverflow.com/questions/15603082/how-to-use-kbhit-and-getch-c-programming – Weather Vane Nov 21 '14 at 21:30
  • @WeatherVane That other question is tagged *windows* and *visual-C++*... on other platforms, `kbhit()` isn't usually available. – Dmitri Nov 21 '14 at 22:35
  • @Dmitri, *other platforms*? OP did not tag a platform. If you have a better answer then post it. – Weather Vane Nov 21 '14 at 23:56
  • @WeatherVane Right.. since he didn't indicate the platform, we don't know that `kbhit()` is available. Also, I didn't downvote.. just speculated about why this answer got downvoted when that other answer didn't (after you brought it up). – Dmitri Nov 22 '14 at 00:10
  • Well perhaps OP can try it and report back. It might be for a massively compatible mega universal solution, or it might be for his own local needs. – Weather Vane Nov 22 '14 at 00:23
  • @Dmitri I have noticed that any non-standard Linux function gets a ding but non-standard Windows functions get a dong. Please stop banging that drum. – Weather Vane Feb 01 '18 at 23:02