"Amit Gupta" <em*******@gmai l.comwrote in message
news:11******** *************@a 75g2000cwd.goog legroups.com...
[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 Tstd::vector<TS tringToVector( const std::string& Str )
{
std::istringstr eam iss( Str );
return std::vector<T>( std::istream_it erator<T>(iss),
std::istream_it erator<T>() );
}
or a more sophisticated version:
//////////////////////////////////////////////////////////////////////////////
inline std::vector<std ::stringTokeniz eString( const std::string& Text,
const std::string& Delimiters )
// Tokenize a passed string with respect to the provided delimiters
//
// e.g.
// string Line = "this_dog_i s mine";
// string Delimiters = " ,:_;#";
// vector<stringWo rdList = TokenizeString( Line, Delimiters );
//////////////////////////////////////////////////////////////////////////////
{
std::vector<std ::stringWordLis t;
std::string::si ze_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::np os ) {
End = Text.find_first _of( Delimiters, Begin );
if( End == std::string::np os ) { // we'v reached the end without
finding another delimiter
End = Text.length();
}
Word.assign( Text.begin() + Begin, Text.begin() + End );
WordList.push_b ack( Word );
Begin = Text.find_first _not_of( Delimiters, End);
}
return WordList;
};
Cheers
Chris