【问题标题】:What's c++11/14/17 equivalence to C function of ltoa/itoa?c++11/14/17 等价于 ltoa/itoa 的 C 函数是什么?
【发布时间】:2020-01-09 21:38:24
【问题描述】:

C++11/14/17 提供了从 string 到 int/long 的函数,但是反过来呢?

我希望将整数转换为二进制字符串,然后打印出来,例如:

int i = 127;
char buf[20];
ltoa(i, buf, 2);
printf("%032s\n", buf);

我可以看到

00000000000000000000000001111111

目前我只能在不同的平台上使用C风格的函数,比如在linux上我有ltoa,在windows上,_itoa_s(不能更丑)...

但是 c++ 呢?

非常感谢。

【问题讨论】:

  • itoa()ltoa() 也不是标准 C 的一部分。在 C 中,您将使用像 sscanf() 这样的函数。在 C++ 中,您可以使用字符串流 (std::istringstream)。

标签: c++ string function binary integer


【解决方案1】:

在 C++17 中,我们有 to_chars:

int i = 127;
char buf[20];
auto [p, e] = std::to_chars(buf, buf + 20, i, 2);

前两个参数的类型为char*,表示缓冲区。第三个参数是数字。最后一个参数是基数。这与ltoa 基本相同。

p 是结束指针。 e 是错误代码。请注意,字符串不是以 null 结尾的。

(live demo)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 2014-06-18
    • 1970-01-01
    相关资源
    最近更新 更多