c++ - string和char*到底能不能转换呢?

浏览:41日期:2023-05-02

问题描述

我一直想的是利用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来转换。可是尴尬的是并没有读到什么信息。这是为什么呢?

问题解答

回答1:

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

回答2:

用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;回答3:

char buff[1024]={0};strncpy(buff,str.c_str(),str.length());//string to charstr.assign(buff);//char to string可以考虑动态分配buff空间。回答4:

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

相关文章: