c++ - 不使用 ASCII 将 int 转换为 char

标签 c++ c

<分区>

例如,我如何将小于 10 的 int 转换为 char :
5 -> '5'
(不使用 ASCII 表将 int 转换为 char)

最佳答案

由于数字在标准字符集中总是连续的,您可以这样写:

int number = 5;
int character = number + '0';

/* Here, character == '5' */

例如,参见 C11 标准。

n1570, § 5.2.1 Character sets

The 10 decimal digits: 0 1 2 3 4 5 6 7 8 9

[...]

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

这同样适用于 C++。

n3337, § 2.3 Character sets

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

关于c++ - 不使用 ASCII 将 int 转换为 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17320769/

相关文章:

c++ - 使用 const_cast 消除常量

c++ - 如何捕获最多N次的重复组?

c++ - 如何比较两个 Compare of two std::set

c++ - 我如何告诉 GCC 为 -l 使用自定义库而不是系统库?

c - 是否有与 Perl 的 Carp 模块等效的 C 语言?

c - 对变量使用单引用运算符和双引用运算符有什么区别?

c++ - 非常小方阵的特征线性求解器

c++ - 如何在 CMake 中添加 "-l"(ell) 编译器标志

c - 类函数宏的参数名称中的前导下划线是否有意义?

c - 有没有一种简单的方法来清除 C 中的管道