// split_iterator.cpp // Demonstration of the split function from the Koening/Moo text // Using an iterator. (page 103) // Ray S. Babcock 11/02/01 // #include #include #include #include vector split(const string&); bool space(char); bool not_space(char); int main(void) { string s; // read and split each line of input while (getline(cin, s)) { vector v = split(s); // write each word in v for(vector::size_type i = 0; i != v.size(); ++i) cout << v[i] << endl; } return 0; } // true if the argument is whitespace, false otherwise bool space(char c) { return isspace(c); } // false if the argument is whitespace, true otherwise bool not_space(char c) { return !isspace(c); } vector split(const string& str) { typedef string::const_iterator iter; vector ret; iter i = str.begin(); while (i != str.end()) { // ignore leading blanks i = find_if(i, str.end(), not_space); // find end of next word iter j = find_if(i, str.end(), space); // copy the characters in [i,j) if (i != str.end()) { ret.push_back(string(i,j)); } i = j; } return ret; }