tags:

views:

125

answers:

3

Hi, 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

+1  A: 

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

reko_t
if I write a cin first before getline(); e.g. cin >> var1; getline(cin, var2); it will get input for var1, but skip var2
starcorn
+2  A: 

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);
Samuel_xL
thanks for the help
starcorn
A: 

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.

Evän Vrooksövich
thanks I think understand it more now
starcorn