c有两个函数: c_str (和data )。
在处理短字符串时,直接调用这两个函数没有问题。 调用格式如下:
STD :3360 stringstr=' helloword '; char* p1=str.c_str (; char* p2=str.data (; 但是,字符串长的情况下,如果使用这两个函数,被转换的char*会变成乱码,但是采用以下方式也完全没有问题,所以在此记录:
char * strc=new char [ strlen (str.c _ str () )1]; strcpy(strc,str.c_str ) ); 综上所述,从c string乱码为char *
这里需要注意:
如果string迁移到const char*,且字符很长,则也无法使用上述第二种方法。 strcpy报告错误。
在这种情况下,可以使用以下格式:
常数字符串; 常数char * str; str=strdup(s.c_str ) )原因: s.c_str ) )返回垃圾指针,s会因为已经解析了语法而乱码。
参考: https://www.cn blogs.com/ye longsan/p/4263605.html