gpt4 book ai didi

C程序: Convert string of chars representing numbers to ints

转载 作者:行者123 更新时间:2023-11-30 14:51:27 24 4
gpt4 key购买 nike

我正在学习 C,我正在尝试让一个玩具示例工作。我的假用例给出了一个字符字符串,其中每个字符代表一个 int,循环遍历该字符串的每个字符并将其转换为 int。到目前为止我尝试过的方法都没有成功。

编辑:原始问题经过编辑,现在包含一个 main() ,以允许响应者根据评论中的建议编译和使用 strtol

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv) {
char *charNums = "12345";
int num, num2, num3, i, n = strlen(charNums);
char *ptr = charNums;

for (i = 0; i < n; i++) {
num = atoi(&charNums[i]);
num2 = atoi(ptr);
num3 = strtol(ptr, NULL, 10);
printf("\ncharNums[%d] = %c (the expected value but as an int not a char)\n num = %d\n num2 = %d\n num3 = %d\n",
i, charNums[i], num, num2, num3);
ptr++;
}
return 0;
)

编辑:显示C代码的编译方法以及程序执行

gcc -o soQuestion main.c
./soQuestion
charNums[0] = 1 (the expected value but as an int not a char)
num = 12345
num2 = 12345
num3 = 12345

charNums[1] = 2 (the expected value but as an int not a char)
num = 2345
num2 = 2345
num3 = 2345

charNums[2] = 3 (the expected value but as an int not a char)
num = 345
num2 = 345
num3 = 345

charNums[3] = 4 (the expected value but as an int not a char)
num = 45
num2 = 45
num3 = 45

charNums[4] = 5 (the expected value but as an int not a char)
num = 5
num2 = 5
num3 = 5

感谢任何反馈。

编辑:该程序的预期结果是将字符串“12345”中的每个字符转换为 1 2 3 4 5 的单个整数,以便我可以对它们进行数学运算,例如对它们求和1 + 2 + 3 + 4 + 5 = 15

最佳答案

在执行 subtraction 时,您可以将字符视为数字这样:

int diff = c - '0';  //c is a character. 
//Avoid using hard code values like 48 in place of '0'.
//as they less readable.

那么diff什么也不是,只是积分值。

关于C程序: Convert string of chars representing numbers to ints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306747/

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