For reference I have already looked at Why does std::getline() skip input after a formatted extraction?
I want to understand cin and getline behavior. I am imagining cin and getline to be implemented with a loop over the input buffer, each iteration incrementing a cursor. Once the current element of the input buffer equals some "stopping" value (" " or "\n" for cin, "\n" for getline), the loop breaks.
The question I have is the difference between the reading behavior of cin and getline. With cin, it seems to stop at "\n", but it will increment the cursor before breaking from the loop. For example,
string a, b;
cin >> a;
cin >> b;
cout << a << "-" << b << endl;
// Input: "cat\nhat"
// Output: "cat-hat"
So in the above code, the first cin read up until the "\n". once it hit that "\n", it increments the cursor to the next position "h" before breaking the loop. Then, the next cin operation starts reading from "h". This allows the next cin to actually process characters instead of just breaking.
When getline is mixed with cin, this is not the behavior.
string a, b;
cin >> a;
getline(cin, b);
cout << a << "-" << b << endl;
// Input: "cat\nhat"
// Output: "cat-"
In this example, the cin reads up to the "\n". But when getline starts reading, it seems to be reading from the "\n" instead of the "h". This means that the cursor did not advance to "h". So the getline processed the "\n" and advances the cursor to the "h" but does not actually save the getline to "b".
So in one example, cin seems to advance the cursor at "\n", whereas in another example, it does not. getline also exhibits different behaviors. For example
string a, b;
getline(cin, a);
getline(cin, b);
cout << a << "-" << b << endl;
// Input: "cat\nhat"
// Output: "cat-hat"
Now getline actually advances the cursor on the "\n". Why is there different behavior and what is the actual implementation of cin vs getline when it comes to delimeter characters?