The most robust advice is to never mix formatted I/O (e.g. using operator >>
) with line oriented input on the same stream (e.g. getline()
) or with character oriented input (e.g. cin.get()
).
The reason is that the different styles of input function respond to newlines differently. Formatted I/O tends to stop and leave a newline in the stream (where it will be encountered first up by getline()
in your code) whereas line oriented input will tend to respond immediately to any newline and discard it.
So change cin >> t
to
string temp_string;
getline(cin, some_string);
istringstream some_stream(some_string); // from <sstream>
some_stream >> t;
The above can be placed in a separate function if you find yourself doing such things frequently.
When combined with the code in your loop, this will only ever interact directly with cin
using line-oriented input, which will avoid the sort of confusion you are seeing.
Using tricks like cin.ignore()
or stream manipulators (e.g. getline(cin << std::ws, s)
will be fragile, depending on how other code (before or after yours) interacts with the stream.