Sign in to follow this  


Recommended Posts

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 this post

Link to post
Share on other sites
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 this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this