gpt4 book ai didi

c++ - 如何将整数字面显示为字符

转载 作者:太空狗 更新时间:2023-10-29 23:53:46 24 4
gpt4 key购买 nike

我有一个整数 1,我想在 C++ 中将它显示为字符“1”。到目前为止,我只设法将它从整数 65 转换为字符“A”。你如何阻止它?

最佳答案

int theDigit = 1;
char ch = theDigit+'0';

这是有效的,因为它保证1字符序列 '0'...'9' 是连续的,所以如果你将您的数字添加到“0”,您将获得相应的字符。显然这只适用于单个数字(如果 theDigit 是例如 20 你会得到一个不相关的字符),如果你需要将整数转换为字符串你需要 snprintf (在 C 中)或 string streams (在 C++ 中)。


  1. C++11,[lex.charset] ¶3:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com