0

Accepting string inputs?

why does a work but not b? int main() { string a = "I am learning C++"; string b; cin >> b; //user inputs I am learning C++ cout << a << endl; cout << b << endl ; return 0; } output is .... I am learning C++ I why does b not output the full sentance?

2nd Nov 2016, 11:01 PM
Aaron
2 RĂ©ponses
+ 1
I have not much eperience with c++ but the problems seems to be the space. Once you hit space the string cuts. So in the cin only goes a word, not a sentance. I found the answer: This only reads in the next token. In C++ iostreams, tokens are separated by whitespace, so you get the first word. You probably want getline, which reads an entire line into a string: getline(cin, str);
2nd Nov 2016, 11:27 PM
Florian Schwarzer
+ 1
because cin read only one word, it ignores the white space and the rest. So you mustn't write cin>>b, but getline(cin, b);
2nd Nov 2016, 11:33 PM
Leo Flame
Leo Flame - avatar