[SNIP]
#include <string.h>
int main()
{
char *token;
char *line = "LINE TO BE SEPARATED";
char *search = " ";
/* Token will point to "LINE". */
token = strtok(line, search);
/* Token will point to "TO". */
token = strtok(NULL, search);
}
Hello,
John already pointed out what to do but I just want to add a general remark.
Using strtok() might not be the best solution for tokenizing especially if
you use C++. You might be tempted for example to attempt to call strtok()
with string object and thus end up doing somethin like this
strtok( line.c_str(), search);
Even though the line above causes undefined behavior as strtok will attempt
to modify the data of the string object, I have seen it working on some
platforms. This easily leads to troublesome confidence that it "works" and
you can easily find yourself in trouble one day, when it breaks.
Thus, you might consider doing a simple tokenizer using stringstreams if
applicable:
// std::string str = "1 2 3 4";
// std::vector<int> vec = StringToVector<int>(str);
template <class T> std::vector<T> StringToVector( const std::string& Str )
{
std::istringstream iss( Str );
return std::vector<T>( std::istream_iterator<T>(iss),
std::istream_iterator<T>() );
}
or a more sophisticated version:
//////////////////////////////////////////////////////////////////////////////
inline std::vector<std::string> TokenizeString( const std::string& Text,
const std::string& Delimiters )
// Tokenize a passed string with respect to the provided delimiters
//
// e.g.
// string Line = "this_dog_is mine";
// string Delimiters = " ,:_;#";
// vector<string> WordList = TokenizeString( Line, Delimiters );
//////////////////////////////////////////////////////////////////////////////
{
std::vector<std::string> WordList;
std::string::size_type Begin, End;
std::string Word;
Begin = Text.find_first_not_of( Delimiters ); // skip blanks or whatever
one finds at the beginning
while( Begin != std::string::npos ) {
End = Text.find_first_of( Delimiters, Begin );
if( End == std::string::npos ) { // we'v reached the end without
finding another delimiter
End = Text.length();
}
Word.assign( Text.begin() + Begin, Text.begin() + End );
WordList.push_back( Word );
Begin = Text.find_first_not_of( Delimiters, End);
}
return WordList;
};
Cheers
Chris