尝试对字符串使用“strtok”时出错 [英] Error trying to use 'strtok' for a string

查看:736
本文介绍了尝试对字符串使用“strtok”时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

int main(){
char * tok;
string s =Ana和Maria正在跳舞。
tok = strtok(s.c_str(),);
while(tok!= NULL){
cout<< tok<< ;
tok = strtok(NULL,);
}
return 0;
}

我收到此错误:

 :9:29:错误:从'const char *'到'char *'无效转换[-fpermissive] 
在ceva包含的文件中。 cc:2:0:
348:14:错误:初始化'char * strtok(char *,const char *)'的参数1 [-fpermissive]
/ pre>

解决方案

strtok()在它的解析中是破坏性的(即在解析它时会写入你正在解析的字符串),所以它需要一个 char * 作为参数,而不是 const char *



c_str()会返回 const char * ,因为它不希望您写入它返回的缓冲区。



解析的方法是 strdup()(即复制)你想要工作的缓冲区并解析,即

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

记住要在完成后释放副本。 / p>

#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;
}

And I'm getting this error:

: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() is destructive in its parsing (ie it writes to the string you're parsing while you're parsing it), so it takes a char* as a parameter, not a const char*.

c_str() returns a const char* since it does not expect you to write to the content of the buffer it returns.

A way to do the parsing is to strdup() (ie copy) the buffer you want to work and parse that, ie;

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

Remember to free the copy once you're done with it.

这篇关于尝试对字符串使用“strtok”时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆