为什么这个代码不能将std :: array转换为std :: string而不显示任何内容?

wee*_*eeo 2 c++ arrays string casting

我正在使用此模板将我更改std::array为字符串.为什么不打印出任何东西?

#include <iostream>
#include <string>
#include <array>

template<std::size_t N>
std::string to_string_2(std::array<char, N> const& arr) {
  const char* str = reinterpret_cast<const char*>(arr.data());
  return std::string( str, str+N );
}
int main()
{
   std::array<char, 16> state = {1,2,3,4,5,6,7,8,9,0,11,12,13,14,15,0};
   std::cout << to_string_2(state) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

tem*_*def 8

您正在创建一个数字值在1到16之间的字符数组.这些是非打印字符,因此您不应该看到任何内容.

尝试将其值更改为显示的字符,例如"A",并查看是否可以解决问题.

希望这可以帮助!