#include <iostream>
#include <string.h>
using namespace std;

int main() {
char *tok;
string s = "Ana and Maria are dancing.";
tok = strtok(s.c_str(), " ");
while(tok != NULL) {
    cout << tok << " ";
    tok = strtok(NULL, " ");
}
return 0;
}

我收到此错误:
:9:29: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
In file included from ceva.cc:2:0:
348:14: error: initializing argument 1 of ‘char* strtok(char*, const char*)’ [-fpermissive]"

最佳答案

strtok()的解析是破坏性的(即,它在解析时会写入要解析的字符串),因此它将char*作为参数,而不是const char*
c_str()返回const char*,因为它不希望您写入它返回的缓冲区的内容。

解析的一种方法是strdup()(即复制)您要使用的缓冲区并对其进行解析,即;

char* buf = strdup(s.c_str());
tok = strtok(buf, " ");
...

完成操作后,请记住要释放副本。

关于c++ - 尝试对字符串使用 'strtok'时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16495527/

10-11 22:42
查看更多