我一直想的是利用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来转换。
可是尴尬的是并没有读到什么信息。
这是为什么呢?
大家讲道理2017-04-17 13:50:51
The content returned by c_str cannot be modified, even if it is cast.
http://www.cplusplus.com/reference/string/string/c_str/
PHP中文网2017-04-17 13:50:51
If you use c
, you should make good use of the c
interface. And judging from your appearance, you can use c++
without learning it at all. Even if you want to write 面向过程风格
's c++
, you still have to learn it...
string buf = new char[1023];
read(fd,const_cast<char*>(buf.c_str()),1024);
You can replace the above with this,
char buf[1024];
read(fd, buf, 1024);
// cout <<string(buff)<<endl; // 但是这样你要再转换成string就没必要了,除非你以后还要用到这个值
Also c++
it is not recommended to use forced type conversion, of course the following conversion is purely wrong
// string buf2 = (string)buf;
// 应该是这样调用构造函数
// string buf2 = string(buf);
// 或者隐式调用构造函数
// string buf2 = buf;
黄舟2017-04-17 13:50:51
char buff[1024]={0};
strncpy(buff,str.c_str(),str.length());//string to char
str.assign(buff);//char to string
可以考虑动态分配buff空间。
怪我咯2017-04-17 13:50:51
As mentioned on the first floor, string::c_str() returns a const char* pointer, which points to the first address of a string object. Since it is a const char* type, of course the content of the address it points to cannot be Modified, so nothing can be read.