Reputation: 89
I am actually trying to loop a menu. on the given character my program should respond according to my logic. on press '0' the program should exit, on '1' it should take some new values (which i am taking through a function) and on '2' it should print those values taken. The loop works fine for the first iteration, but when it starts again, it misses a command of input (cin.get) and continues with the flow - doing nothing for this time- and then it gets fine again. I am not sure what is happening.
This is my code
#include <iostream>
#include <string>
using namespace std;
//prototypes
void init_subscriber(Subscriber &s);
void print_subscriber(Subscriber &s);
int main()
{
char option = ' ';
Subscriber s1;
while (option != '0')
{
cout << "Introduce Options:" << endl;
cout << "(0) exit" << endl << "(1) Add subscriber" << endl << "(2) Print subscribers info" << endl << endl;
cin.get(option);
if (option == '1')
{
init_subscriber(s1);
}
else if (option == '2')
{
print_subscriber(s1);
}
else if (option == '0')
{
option = '0';
}
}
cout << "we are out of while" << endl;
cin.get();
return 0;
}
Upvotes: 1
Views: 143
Reputation: 409176
Think about this: The cin.get
function gives you a single character in the input buffer, but you press two keys to enter a single number: The digit and the Enter key. That Enter key will add a newline in the input buffer and it will not be discarded. So the next iteration cin.get
will read that newline.
The solution? After cin.get
ask cin
to ignore characters until (and including) a newline.
Upvotes: 4