starcorn
starcorn

Reputation: 8551

C++ string question

I got a really simple question.

string str;
cin >> str;
cout << str;

if I type in "Hello World" the output I get is only "Hello". I know it probably has to do with whitespace. So my question is how I should write if I want the whitespace as well?

I have also tried to use getline(cin, str); but it will only read input first time and skip the rest

Upvotes: 1

Views: 292

Answers (3)

lyricat
lyricat

Reputation: 1996

The problem is, operator >> leaves the next space/newline/whatever in the input buffer. So if you call cin >> str followed by getline( cin, str ), the getline operation will see the first character in the input buffer is a newline, and stop.

Upvotes: 0

KeatsPeeks
KeatsPeeks

Reputation: 19337

getline(cin, str) should work, but you may have to purge the input buffer before calling it if you encounter "char skipping":

std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
std::string str;
std::getline(std::cin, str);

Upvotes: 2

reko_t
reko_t

Reputation: 56450

getline(cin, str) is the correct way. What do you mean it will only read input the first time and skip the rest?

Upvotes: 1

Related Questions