That is because
getline (string) - C++ Reference[
^] and the
istream::operator>> - C++ Reference[
^] behave differently.
getline()
reads until the delimiting character (newline
\n
by default) is read and discards that character.
The
istream >>
operator with strings skips leading white spaces (like space, tab, newline) and reads then until a white space character is encountered. That white space character is not read but left in the input buffer.
You are calling
cin>>n;
initially. That will read the entered number but will let the newline character in the input buffer. When calling
getline()
afterwards, that will read the newline as first character and stop. That is: you got an empty string. When using the
istream >>
operator instead, it will skip the newline character and read the content of the next line.
Due to this different behaviour it is not recommended to mix
getline()
and
>>
operator calls for the same stream.