c++ - 尝试将 'strtok' 用于字符串时出错

标签 c++ strtok

#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/

相关文章:

c++ - 没有虚拟继承的多重继承

c++ - 用c++同时读写同一个文件

c++ - what():basic_string::_ M_construct null无效

c - 在解析 HTML/XML 中的标签时,我想为 '<' 初始化 strtok,但有时我只需要处理原始文本

c++ - 将 token 存储到数组中

c++ - 删除 CallBack 函数中 new 创建的指针

c++ - 从 ‘const char*’ 到 ‘char*’ [-fpermissive] 的无效转换; VTK-7.1.1编译错误

c++ - 在容器中存储 boost::function 对象

c - ANSI C : How to split a string by newline and get a random line

c - 段错误: 11 while trying to parse string