#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*
作为参数,而不是一个常量字符*
。
c_str()
返回一个 const char*
,因为它不希望您写入它返回的缓冲区的内容。
进行解析的一种方法是 strdup() (即复制)你想要工作的缓冲区并解析它,即;
char* buf = strdup(s.c_str());
tok = strtok(buf, " ");
...
记得在完成后释放拷贝。
关于c++ - 尝试将 'strtok' 用于字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495527/