You are mixing >> with getline.
>> will stop as soon as it finds whitespace following non-whitespace. Any leading whitespace is discarded, and trailing whitespace is left in the buffer.
Example... if the user inputs
[space][space]foo[newline]
Then:
- the first 2 spaces are discarded
- the >> operator will extract "foo" (with no spaces)
- the newline remains inside the cin buffer.
On the other hand.. getline() extracts the entire line up to the next newline character. Whitespace is preserved... and the trailing newline is discarded.
Example... if the user inputs the same thing:
[space][space]foo[newline]
- getline extracts "[space][space]foo"
- the newline is discarded
- cin buffer is empty
With that out of the way.... let's look at your program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// line 12:
cin >> code;
// user inputs: "encode\n" (\n is the newline when they press enter)
// result... code=="encode", cin buffer has "\n" in it
// line 17:
cin >> message;
// user inputs "test1 test2\n"
// cin buffer now has "\ntest1 test2\n"
// result... message="test1"
// leading \n is discarded
// cin buffer has " test2\n" still in it
// line 18:
getline(cin, message);
// user has no chance to input anything, as cin buffer is not empty
// cin buffer still contains " test2\n"
// result... message=" test2"
// trailing \n is discarded
// cin buffer is now empty
|
The solution
When you need to have >> followed by a getline... put a cin.ignore between them. cin.ignore will discard any lingering newlines in the buffer that the >> operator left there.
EDIT:
Man did I get ninja'd like 4 times?
EDIT 2:
long double main wrote: |
---|
which is why we need the cin >> ws |
!! That's neat! I never knew about that!