The code std::cin>>name;
is equivalent to operator>>(std::cin, name);
this calls the function (declared in <string>
):
template <class CharT, class Traits, class Allocator>
std::basic_istream<CharT, Traits>& operator>>(
std::basic_istream<CharT, Traits>& is,
std::basic_string<CharT, Traits, Allocator>& str);
With the template arguments CharT = char
and Traits = std::char_traits<CharT>>
As per the documentation at:
operator<<,>>(std::basic_string)
This will first trim whitespace, then read until the first whitespace character is found (though this is not extracted from the stream).
As such it only reads ‘Jai’, even though ‘Jai Simha Verma\n’ is the (unread) contents of the stream.
At your call getline (std::cin, name);
the stream will contain ‘ Simha Verma\nJai Simha Verma\n’, but getline();
stops reading at the first newline character (it will extract it, but not append it to name
), so it sets name
to ‘ Simha Verma’ (including the leading space).
After this, the (unread) contents of std::cin
will be ‘Jai Simha Verma\n’.
I am not sure what behaviour you would like so I am unable to suggest how to achieve this, rather I have merely explained what is happening.