Mys*_*ial 354
本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;
Run Code Online (Sandbox Code Playgroud)
sta*_*her 54
另一种解决方案可能如下所示,
char arr[] = "mom";
std::cout << "hi " << std::string(arr);
Run Code Online (Sandbox Code Playgroud)
这避免了使用额外的变量.
Yol*_*ola 28
在最高投票的答案中错过了一个小问题.也就是说,字符数组可能包含0.如果我们将使用带有单个参数的构造函数,如上所述,我们将丢失一些数据.可能的解决方案是:
cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;
Run Code Online (Sandbox Code Playgroud)
输出是:
123
123 123
Cri*_*ian 10
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main ()
{
char *tmp = (char *)malloc(128);
int n=sprintf(tmp, "Hello from Chile.");
string tmp_str = tmp;
cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;
free(tmp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
OUT:
H : is a char array beginning with 17 chars long
Hello from Chile. :is a string with 17 chars long
Run Code Online (Sandbox Code Playgroud)