gpt4 book ai didi

c++ - 在 C 中将 char 转换为 int

转载 作者:太空宇宙 更新时间:2023-11-04 05:26:23 25 4
gpt4 key购买 nike

在发布这个问题之前,我已经搜索了很长时间。不过,这个问题的答案应该相当简单,因为我是一个 super 新手 atm。

我有一个 char*,我希望用户在其中输入一些数字(超过 20 个),然后可以具体调用这些数字。

这是我试过的:

    char* digits = GetString();
int prime = digits[0];

当我验证这是否适用于 printf 时,我发现素数已变为 0。

    printf("prime:%d\ndigits:%c\n",prime, digits[0]);

为什么会这样,我可以做些什么来实现它?

编辑:制作一个 int 数组并使用 GetLongLong 可能更容易吗?

最佳答案

C 或 C++ 都不能保证将使用什么值对字符 0 进行编码,但都保证数字将是连续且有序的,因此(例如)digits[0]- 48 可能有效也可能无效,但 digits[0] - '0' 保证有效(假设 digits[0] 实际上包含一个数字,当然)。

C++ 标准 (§2.3/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.

至少从 C99 开始,C 标准具有相同的措辞,但在 §5.2.1/3。

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

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