To iterate over the words of a string in C++, you can use std::istringstream along with the extraction operator (>>), which splits the string by whitespace (spaces, tabs, newlines). Here’s a step-by-step solution:
1. Include Necessary Headers
#include <iostream>
#include <string>
#include <sstream> // Required for std::istringstream
using namespace std;2. Use std::istringstream to Split the String
int main() {
    string input = "Hello   world  C++   programmers!";
    // Create a string stream from the input
    istringstream iss(input);
    string word;
    while (iss >> word) { // Extract words one by one
        cout << "Word: " << word << endl;
    }
    return 0;
}Output
Word: Hello
Word: world
Word: C++
Word: programmers!Key Notes:
- Whitespace Handling: The extraction operator (>>) automatically skips all whitespace (spaces, tabs, newlines).
- Edge Cases:
- Leading/trailing whitespace is ignored.
- Consecutive whitespace is treated as a single delimiter.
- Empty strings produce no output.
Alternative Method: Split by Custom Delimiters
If you need to split by a specific delimiter (e.g., commas), use std::getline with a delimiter:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
    string input = "apple,banana,cherry";
    char delimiter = ',';
    istringstream iss(input);
    string word;
    while (getline(iss, word, delimiter)) {
        cout << "Word: " << word << endl;
    }
    return 0;
}Output
Word: apple
Word: banana
Word: cherrySummary
| Method | Behavior | 
|---|---|
| >>Operator | Splits by any whitespace (default). | 
| getline | Splits by a custom delimiter (e.g., ,,;, etc.). | 
Choose the method based on whether you need to split by whitespace or a custom delimiter!