Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将字符数组转换为字符串? 使用字符串,将C++ >代码>字符串 >转换为char数组。然而,如何做相反的事情呢_C++_String_Char_Arrays - Fatal编程技术网

如何将字符数组转换为字符串? 使用字符串,将C++ >代码>字符串 >转换为char数组。然而,如何做相反的事情呢

如何将字符数组转换为字符串? 使用字符串,将C++ >代码>字符串 >转换为char数组。然而,如何做相反的事情呢,c++,string,char,arrays,C++,String,Char,Arrays,我有一个char数组,比如:chararr[]=“这是一个测试”要转换回: string str=“这是一个测试该string类有一个构造函数,它接受以NULL结尾的C字符串: char arr[ ] = "This is a test"; string str(arr); // You can also assign directly to a string. str = "This is another string"; // or str = arr; 另一个解决方案可能是这样

我有一个char数组,比如:
chararr[]=“这是一个测试”要转换回:

string str=“这是一个测试

string
类有一个构造函数,它接受以NULL结尾的C字符串:

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

// or
str = arr;

另一个解决方案可能是这样的

char arr[] = "mom";
std::cout << "hi " << std::string(arr);
char arr[]=“mom”;

std::cout在最受欢迎的答案中遗漏了一个小问题。即,字符数组可能包含0。如果我们像上面指出的那样使用带单个参数的构造函数,我们将丢失一些数据。可能的解决方案是:

cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;

cout这两种方式都可以。重载赋值运算符采用
const char*
,因此您可以向其传递字符串文字或字符数组(衰减为该字符串)。@kingsmasher1:严格来说,
“hello world”
形式的字符串是数组。如果您使用
sizeof(“hello world”)
它将给出数组的大小(12),而不是指针的大小(可能是4或8)。请注意,这仅适用于以常量NULL结尾的C字符串。
字符串
构造函数将不适用于声明为
无符号字符*缓冲区
的传递参数字符串,这在字节流处理库中非常常见。不需要任何常量。如果您有任何字符的字节缓冲区类型,您可以使用另一个构造函数:
std::string str(buffer,buffer+size);
,但在这种情况下,最好还是使用
std::vector
。虽然这可能很明显:
str
在这里不是转换函数。它是字符串变量的名称。您可以使用任何其他变量名称(例如
string foo(arr);
)。转换是由std::string的构造函数完成的,该构造函数被隐式调用。您能在答案中指出这与接受的答案my Misticial有什么不同吗?@owlstead请查看编辑。我只是将我的答案放在这里,因为当我第一次看到这个页面寻找答案时,我希望看到它。如果有人像我一样愚蠢的话遇到此页面,但无法通过查看第一个答案建立连接,我希望我的答案能够帮助他们。这通常不适用于字符数组,只有在字符数组以0结尾时才适用。如果无法确保字符数组以0结尾,请向
std::string
构造函数提供长度,如.Thi中所示如果您使用
std::string
作为二进制数据的容器,并且无法确定数组是否包含'\0',或者如果字符串数组不包含'\0',Where is free(tmp),则s是一个更好的答案?字符串是否处理了这个问题?好问题。我认为free应该存在,因为我使用的是malloc。
H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long
cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;