cin and getline skipping input [duplicate]
If you're using getline
after cin >> something
, you need to flush the newline out of the buffer in between.
My personal favourite for this if no characters past the newline are needed is cin.sync()
. However, it is implementation defined, so it might not work the same way as it does for me. For something solid, use cin.ignore()
. Or make use of std::ws
to remove leading whitespace if desirable:
int a;
cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
//discard characters until newline is found
//my method: cin.sync(); //discard unread characters
string s;
getline (cin, s); //newline is gone, so this executes
//other method: getline(cin >> ws, s); //remove all leading whitespace
The structure of your menu code is the issue:
cin >> choice; // new line character is left in the stream
switch ( ... ) {
// We enter the handlers, '\n' still in the stream
}
cin.ignore(); // Put this right after cin >> choice, before you go on
// getting input with getline.