# std::string

## Recommended Posts

klayAlloy    150
I'm need to prompt the user for a sentence and store the sentence in a std::string. I'm then going to seperate each word out of the sentence into a std::vector of strings. I tried using std::cin, but the stream closes after the first space between words. Any help on how to approach this would be great?

##### Share on other sites
klayAlloy    150
I think I found the answer:
std::string temp;std::getline(std::cin, temp)

##### Share on other sites
Zahlman    1682
0) That isn't "using std::cin". If I write "foo + bar" to add foo to bar, am I "using foo"? What's being used is the *operator*, std::cin::operator>>.

1) The stream doesn't close after you read a word with that operator. It just doesn't read more than that word, *that time*. If you make another attempt to read, it will read the next word.

It doesn't matter that you're using the console. Operations on a stream are *not synched up* with the console. The stream doesn't "see" any data until the user hits return, because of how the console works, but once that is done, the whole line is "available", and it stays available until all of it gets either read or skipped past.

If you ever had any problems with reading in a number and then trying to get a line of text after that, that's why. Reading the number left the end-of-line character in the stream data. The call to get a line of text saw that EOL character right away.

2) And isn't that just the behaviour you want, if you're trying to "separate out each word into a vector"?

string word;vector<string> sentence;while (cin >> word) { sentence.push_back(word); }

3) That said, std::getline is the proper way to read a line of input, yes.

##### Share on other sites
klayAlloy    150
zahlman: Thank you for the response. I guess I still have a ways to go before I get streams down. Slowly, very slowly, I'm learning.