1

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; } 

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i added "cin.ignore();" after the init_subscribe and print_subscribe funtions, and it seem to work fine. Thanks man!
Another question: In the same program I am trying to print an enum obj. I check for the overloaded cout << , it working but it doesnt return the string but and index of the enum objects. ostream& operator<<(ostream& os, Pass& obj) { os << static_cast<std::underlying_type<Pass>::type>(obj); return os; }
@SarmadAsif If you have a new question, ask a new question. You can include a link to this question if it helps provide context.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.