c++ - string和char*到底能不能转换呢?
PHP中文网
PHP中文网 2017-04-17 13:48:51
0
4
351

我一直想的是利用C++string类封装的函数的便捷性和linux下的C/API结合来
实现某些方法。可是有个问题出现了,每次碰见string和char*之间的转换的时候极为的尴尬。

  #include <iostream>
  #include <stdio.h>
  #include <unistd.h>
  #include <iostream>
  #include <string>
  #include <sys/types.h>          /* See NOTES */
  #include <sys/socket.h>
  #include <arpa/inet.h>
  #include <sys/stat.h>
  #include <fcntl.h>
  using namespace std;


int main(int argc, char const *argv[])
{
 int fd = open("./ok",O_RDWR);

// char buf[1024];
string buf = new char[1023];
read(fd,const_cast<char*>(buf.c_str()),1024);
cout << buf << endl;
// string buf2 = (string)buf;
cout << buf.find_first_of(" ",0);
cout << "*********" << endl;

return 0;
}

read的第二个参数原本是void,一般使用的时候是用char来做的,把独到的信息存储在buf里面,为了以后方便,我希望在这里直接用一个string来存储信息。
我清楚string和char*并不是兼容的,所以我通过const_cast来转换。
可是尴尬的是并没有读到什么信息。
这是为什么呢?

PHP中文网
PHP中文网

认证0级讲师

全部回复(4)
大家讲道理

c_str返回的内容是不能修改的,就算cast了也不行。
http://www.cplusplus.com/reference/string/string/c_str/

Ty80

c就好好使用c的接口,而且看你的样子,完全没学过c++就用,就算要写面向过程风格c++也要学会才行...

string buf = new char[1023];
read(fd,const_cast<char*>(buf.c_str()),1024);

上面的你可以替换成这样,

char buf[1024];
read(fd, buf, 1024); 
// cout <<string(buff)<<endl; // 但是这样你要再转换成string就没必要了,除非你以后还要用到这个值

还有就是c++不推荐使用强制类型转换,当然下面的转换纯粹是错误的

// string buf2 = (string)buf;
// 应该是这样调用构造函数
// string buf2 = string(buf);
// 或者隐式调用构造函数
// string buf2 = buf;
黄舟

雷雷

刘奇

一楼说了,string::c_str()返回的是一个const char*指针,它指向一个string对象的首地址,既然是const char*类型,那么它指向的地址的内容当然是不能被修改的,所以读不到任何东西。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!