There are simpler ways to accomplish this in C++. The strtok
function is a C function and cannot be used with std::string
directly since there is no way to get writable pointer access to the underlying characters in an std::string
. You can use iostream
s to get individual words separated by spaces from a file directly in C++.
Unfortunately the standard library lacks a simple, flexible, efficient method to split strings on arbitrary characters. It gets more complicated if you want to use iostream
s to accomplish splitting on something other than whitespace. Using boost::split
or the boost::tokenizer
suggestion from shuttle87 is a good option if you need something more flexible (and it may well be more efficient too).
Here's a code example reading words from standard input, you can use pretty much the same code with an ifstream
to read from a file or a stringstream
to read from a string: http://ideone.com/fPpU4l
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main() {
vector<string> words;
copy(istream_iterator<string>{cin}, istream_iterator<string>{}, back_inserter(words));
copy(begin(words), end(words), ostream_iterator<string>{cout, ", "});
cout << endl;
}