作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个整数 1,我想在 C++ 中将它显示为字符“1”。到目前为止,我只设法将它从整数 65 转换为字符“A”。你如何阻止它?
最佳答案
int theDigit = 1;
char ch = theDigit+'0';
这是有效的,因为它保证1字符序列 '0'
...'9'
是连续的,所以如果你将您的数字添加到“0”,您将获得相应的字符。显然这只适用于单个数字(如果 theDigit
是例如 20 你会得到一个不相关的字符),如果你需要将整数转换为字符串你需要 snprintf
(在 C 中)或 string streams (在 C++ 中)。
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.
顺便说一句,我想他们并没有仅仅因为 EBCDIC 就要求字母字符中的连续性。
关于c++ - 如何将整数字面显示为字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9220838/
我是一名优秀的程序员,十分优秀!