在一些代码 int8_t[]
类型用于替代的 char[]
.
int8_t title[256] = {'a', 'e', 'w', 's'};
std::string s(title); // compile error: no corresponding constructor
如何正确和安全创建一个 std::string
从?
当我会做的 cout << s;
我想它打印 aews
,因为如果 char[]
类型是通过构造。
在一些代码 int8_t[]
类型用于替代的 char[]
.
int8_t title[256] = {'a', 'e', 'w', 's'};
std::string s(title); // compile error: no corresponding constructor
如何正确和安全创建一个 std::string
从?
当我会做的 cout << s;
我想它打印 aews
,因为如果 char[]
类型是通过构造。
你在这里
int8_t title[256] = { 'a', 'e', 'w', 's' };
std::string s( reinterpret_cast<char *>( title ) );
std::cout << s << '\n';
或者您可以使用还
std::string s( reinterpret_cast<char *>( title ), 4 );
0
,因此它具有252空终止。 std::string
像其他容器可以构成利用对迭代器。 这个构造将使用的隐性转换,如果可用,诸如转换 int8_t
要 char
.
int8_t title[256] = {'a', 'e', 'w', 's'};
std::string s(std::begin(title), std::end(title));
注意,这一解决方案将复制本系列,其中包括未使用的字节。 如果阵列常常大大超过需要,可以寻找零,而不是终结者
int8_t title[256] = {'a', 'e', 'w', 's'};
auto end = std::find(std::begin(title), std::end(title), '\0');
std::string s(std::begin(title), end);