How do I iterate over the words of a string?

I’m trying to iterate over the words of a string.

The string can be assumed to be composed of words separated by whitespace.

Note that I’m not interested in C string functions or that kind of character manipulation/access. Also, please give precedence to elegance over efficiency in your answer.

The best solution I have right now is:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
    string s = "Somewhere down the road";
    istringstream iss(s);

        string subs;
        iss >> subs;
        cout << "Substring: " << subs << endl;
    } while (iss);

Is there a more elegant way to do this?


Leave a Comment