创建std::string从int8_t阵列

0

的问题

在一些代码 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[] 类型是通过构造。

c++ casting char integer
2021-11-23 15:34:12
2

最好的答案

2

你在这里

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 );
2021-11-23 15:45:55

听起来像一个糟糕的想法没有一个明确的空终止数。
dave

@dave和你为什么必须决定,是没有空终止字?
Vlad from Moscow

应该有252空终止在这一阵列。 :-)
Ted Lyngmo

@dave我虽然同样的事情,然后记住,所有失踪都设置初始化 0,因此它具有252空终止。
NathanOliver

啊,对的,没有看到256大小。 这是确定的,那么在这种情况下
dave
1

std::string 像其他容器可以构成利用对迭代器。 这个构造将使用的隐性转换,如果可用,诸如转换 int8_tchar.

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);
2021-11-23 15:38:17

其他语言

此页面有其他语言版本

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................