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