1

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

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

if I write a cin first before getline(); e.g. cin >> var1; getline(cin, var2); it will get input for var1, but skip var2
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.