cin (keyboard buffer problems)

Hello all,
This is my first post. I am a C++ student and am having a really frustrating problem with returning for more keyboard input during a loop.

All of the research I have done so far - and what I have observed on my computer suggests that its the leftover input in the keyboard buffer causing the problem.

I have used cin >> , cin.get(), getline(), cin.ingnore() and a few other things not taught in the class that really did nothing at all.

Here is the problem in in simplest form:
//below is the part in main(). the idea is to call GetNum and put the result in to Num1 and Num2. All of that works fine for the first round Num1. GetNum is long and processes the input, converting characters to real numbers that can be calculated. I wont show that processing because all of that works fine.
The problem is when its time to get the input for Num2, the program just skips on by the input line using cin in any of its forms - into an array of chars or into a stream object from <stream> and sends 0 into Num2. Apparently cin is reading something (or everything) left in the keyboard buffer from the first round. The ultimate question is how to clear the keyboard buffer or look past what is already there?

//get the numbers to be calculated and the operator.
cout << "\tFirst Number ---------------> ";
Num1 = GetNum();
FuncChoice = MenuChoice();
if ((FuncChoice != 'C') && (FuncChoice != 'c'))
cout << "\tSecond Number --------------> ";
Num2 = GetNum();
cout << endl;
did u try inserting cin.ignore(); before Num2=GetNum();
cin.clear(); // Clear flags indicating errors on stream
cin.ignore(INT_MAX, '\n'); // Clear (hopefully) all leftover contents in the stream
// NOW try reading from cin again. 

Try this. You can do the ignore part a little bit 'better' by doing this:

#include <limits>


cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
Last edited on
Topic archived. No new replies allowed.