Sunday, August 2, 2009

C++: How can I store each word from a sentence as an individual string?

If I ask the user to input a sentence, how can I store each word from that sentence as an individual string? I then want to push each word into a queue, so it's not important that I permanently store each word in a separate variable.

C++: How can I store each word from a sentence as an individual string?
Each word is separated by a space. Hence, your objective is tokenize a string (using spaces), and then store those tokens appropriately.





Since this is C++, I'm assuming you have the sentence in a C++ string. Look at http://www.oopweb.com/CPP/Documents/CPPH... and more specifically the string tokenizer section. If you're not familiar with the various C++ string methods look at http://cppreference.com/cppstring/index....








Specifically the logic is this:


Keep looking for the first space in the string you encounter. Obviously, everything from your current position in the string to the first occurence of the space is the word itself. Therefore, that is your token. Move your current position over to where the space is. Repeat the look for the next space process if you haven't reached the end of the string.





Work through the string tokenizer code and you'll understand.
Reply:use argv[]

flamingo plant

No comments:

Post a Comment