cin is the culprit. Even I never know about this like forever man, but it turns out that cin, apart from not being able to read whitespaces, also leaves those trailing whitespaces in the buffer itself (note that leading whitespaces are ignored and completely omitted).
So if you typed
hello (tabspace) (linefeed i.e '\n')
and wanted cin to put that into a string variable,
it would put "hello" into the variable and leave (tabspace) (linefeed) in the buffer.
But wait! linefeed is what getline() uses to mark end of input! So what is happening is that the getline is reading the linefeed ('\n') from the buffer.
Try this:
1 2 3 4 5
|
string foo;
cin >> foo;
getline(cin, foo)
for(auto i: foo)
cout << (int)i;
|
Run that snippet and type in say "Hello (tabspace)(linefeed)" or "Hello(linefeed)"
You will note that getline is reading whitespaces and tabspaces even though it never begun input.
How to solve this? Simply clear the buffer before allowing getline() to take input.
i.e,
put "cin.ignore(INT_MAX, '\n');"
before your getline statements when you are using cin.
That statement reads and discards characters from the buffer until it reaches '\n'.