Possible Duplicate:
Using strtok with a string argument (instead of char*)? 开发者_JAVA百科
When using strtok()
i do the following
char str[300];
while(infile) {
infile.getline(str,300);
char* token=strtok(str," ");
How can i use a string instead of the character array char str[300];
is there a way to use it to be like this,string str;
while(infile) {
infile.getline(str,300);
char* token=strtok(str," ");
I don't think you can, at least not without great care; strtok()
modifies its argument, writing a \0
into it after every recognized token, and generally behaves like a function that's poorly behaved even for C, much less C++. My advice would be to look for a native C++ solution instead.
If you mean an std::string
, you cannot, strtok
only works with char*
.
An easy solution could be that of strdup
your string.c_str
, and pass it to strtok
.
string str;
while(infile)
{
getline(infile, str);
char* token=strtok(&str[0], " ");
}
Clean it ain't, but it will work.
EDIT: My mistake, this may not work in all circumstances.
精彩评论