You know that processing the text efficiently is a very common task in C++, and one very frequently encountered operation is iterating over the words of a string. There are various methods to achieve the iteration over the words. But here, we have discussed the simplest and most effective method to iterate over the words of a string in C++, i.e., the std::stringstream method.
Using the std::stringstream
The std::stringstream is the simplest and most common method, and it treats a string as a stream and uses the extraction operator (>>) to extract words from the string in C++. You can use the std::stringstream when you need to iterate over the simple words that are separated by whitespace. Also, it is an effective method for fast primary text processing.
Example 1:
Output:
In this program, std::stringstream is created with a string. The while loop extracts each word one at a time by treating whitespaces as the boundary between each word, where every word gets printed on a new line.
Example 2:
Output:
In this program, std::stringstream is created with a string. The while loop extracts each word one at a time by treating whitespaces as the boundary between each word, where every word and the total number of words gets printed on a new line.
Note: When you are using the std::stringstream, it is important to handle potential errors and issues. So, to handle the errors, always start by checking if the input string is empty before creating the std::stringstream object because an empty string will give results as no words are being extracted or iterated. Also, you can check the state of a stream using the fail() function to determine that no error occurs in the code.
Conclusion
Every method used for iterating over the words of a string in C++ has its advantages, but the std::stringstream method we have discussed here is very simple and easy to use. This method simply allows you to process the text efficiently by treating a string as a stream. This method also provides you with clear, readable, and concise code, which is very important for C++ programming. So, by learning this method, you can easily iterate over the words of a string in C++.
Some Other Methods to Iterate over Strings in C++