【问题标题】:Printing chars as Integers将字符打印为整数
【发布时间】:2012-06-12 14:29:57
【问题描述】:

我想控制我的ostream 输出的chars 和unsigned char 通过<< 将它们写为字符 还是整数。我在标准库中找不到这样的选项。现在我已经恢复到在一组替代打印函数上使用多个重载

ostream& show(ostream& os, char s) { return os << static_cast<int>(s); }
ostream& show(ostream& os, unsigned char s) { return os << static_cast<int>(s); }

有没有更好的办法?

【问题讨论】:

  • 您希望始终将字符打印为整数还是根据条件打印?
  • 我希望它依赖于类似于ios 状态标志的条件(状态)。
  • 我不明白区分有符号字符和无符号字符的必要性。如果要将其输出为数字,请先将其转换为 int。否则,只需将其打印到 os 即可。
  • 也许可以为此编写自己的io操纵器...
  • cout &lt;&lt; static_cast&lt;uint32_t&gt;(some_char_val);?

标签: c++ formatting ostream interpretation


【解决方案1】:

在 C++20 中,您将能够使用 std::format 来执行此操作:

unsigned char uc = 42;
std::cout << std::format("{:d}", uc); // format uc as integer 42 (the default)
std::cout << std::format("{:c}", uc); // format uc as char '*' (assuming ASCII)

同时可以使用the {fmt} library,基于std::format

免责声明:我是 {fmt} 和 C++20 std::format 的作者。

【讨论】:

    【解决方案2】:

    只是对旧帖子的更新。实际的技巧是使用“+”。例如:

    template <typename T>
    void my_super_function(T x)
    {
      // ...
      std::cout << +x << '\n';  // promotes x to a type printable as a number, regardless of type
      // ...
    }
    

    在 C++11 中你可以这样做:

    template <typename T>
    auto promote_to_printable_integer_type(T i) -> decltype(+i)
    {
      return +i;
    }
    

    信用:How can I print a char as a number? How can I print a char* so the output shows the pointer’s numeric value?

    【讨论】:

      【解决方案3】:

      不,没有更好的方法。更好的方法是采用自定义流操纵器的形式,例如std::hex。然后,您可以关闭和打开整数打印,而无需为每个数字指定它。但是自定义操纵器对流本身进行操作,并且没有任何format flags 可以执行您想要的操作。我想你可以编写自己的流,但这比你现在做的工作要多。

      老实说,最好的办法是查看您的文本编辑器是否具有使static_cast&lt;int&gt; 更易于键入的功能。我假设你会输入很多,否则你不会问。这样,阅读您的代码的人就可以确切地知道您的意思(即,将 char 打印为整数),而无需查找自定义函数的定义。

      【讨论】:

        【解决方案4】:

        我有一个基于how do I print an unsigned char as hex in c++ using ostream? 中使用的技术的建议。

        template <typename Char>
        struct Formatter
          {
          Char c;
          Formatter(Char _c) : c(_c) { }
        
          bool PrintAsNumber() const
            {
            // implement your condition here
            }
          };
        
        template <typename Char> 
        std::ostream& operator<<(std::ostream& o, const Formatter<Char>& _fmt)
          {
          if (_fmt.PrintAsNumber())
            return (o << static_cast<int>(_fmt.c));
          else
            return (o << _fmt.c);
          }
        
        template <typename Char> 
        Formatter<Char> fmt(Char _c)
          {
          return Formatter<Char>(_c);
          }
        
        void Test()
          {
          char a = 66;
          std::cout << fmt(a) << std::endl;
          }
        

        【讨论】:

        • 您当然意识到您编写了 23 行代码(不包括测试人员)以便能够将字符打印为数字,对吗?是不是有点矫枉过正?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-12
        相关资源
        最近更新 更多