开发者

How to use strtok() using a string argumnet instead of character array? [duplicate]

开发者 https://www.devze.com 2023-03-10 07:10 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Using strtok with a string argument (instead of char*)?
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消