将字符打印为整数

8

我希望能够控制通过<<输出charunsigned 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); }

有更好的方法吗?

1
你想始终将字符打印为整数还是根据条件而定? - Andriy
我希望它可以根据一个条件(状态)进行依赖,类似于“iOS”状态标志。 - Nordlöw
4
我不明白区分有符号和无符号字符的必要性。如果你想将其输出为数字,请先将其转换为int类型。否则,只需将其打印到操作系统中即可。 - Neil
也许可以为此编写自己的io操作符... - PlasmaHH
1
cout << static_cast<uint32_t>(some_char_val); cout << static_cast<uint32_t>(some_char_val); - John Dibling
显示剩余3条评论
4个回答

1

这是对一篇旧帖子的更新。真正的技巧是使用“+”。例如:

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;
}

来源: 如何将字符作为数字打印出来?如何打印char*使输出显示指针的数值?


1

没有更好的方法。更好的方法将采用自定义流操作器的形式,例如std::hex。然后,您可以在不必为每个数字指定它的情况下打开和关闭整数打印。但是自定义操作器作用于流本身,并且没有任何格式标志可以做到您想要的。我想您可以编写自己的流,但这比您现在所做的工作要多得多。

老实说,您最好的选择是查看您的文本编辑器是否具有使static_cast<int>更易于键入的功能。我假设否则您会经常输入它,否则您就不会提出这个问题。这样,阅读您的代码的人就知道您的意思(即将字符打印为整数),而无需查找自定义函数的定义。


0

我有一个建议,基于如何使用ostream在C++中打印无符号字符的十六进制值?所使用的技术。

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行代码(不包括测试器),对吧?这有点过度设计了,不是吗? - Neil

0
在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)

与此同时,您可以使用基于其构建的{fmt}库std::format

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接