【问题标题】:Why doesn't this code to convert a std::array to a std::string not display anything?为什么这段将 std::array 转换为 std::string 的代码不显示任何内容?
【发布时间】:2013-06-19 23:38:51
【问题描述】:

我正在使用此模板将我的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;
}

【问题讨论】:

  • std::tr1::array 和 std::array 一样吗?
  • 那么,1 应该转换为'1',15 应该转换为...?
  • @JamesBlack,它是它的先驱。 std::tr1::array 是在 C++11 仍在进行最后润色时实现的。当 C++11 完成时,它被提升为std。我们在 C++14 中推出了 TR2。
  • @chris - 谢谢,我不知道这个前身。

标签: c++ arrays string casting


【解决方案1】:

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

尝试将它们的值更改为可以显示的字符,例如“A”,看看这是否能解决问题。

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    是什么让您认为它不会打印出任何东西?我猜它确实会从您的原始数组中打印出带有 ACSII 代码的字符,但它们恰好对应于您平台上的“不可见”字符,即屏幕上未由可见字形表示的字符。

    您可以将程序的输出重定向到一个文件,然后在十六进制编辑器中打开该文件。我相信您会立即在该文件中发现您的字符代码序列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-28
      相关资源
      最近更新 更多