【发布时间】:2018-01-17 17:26:10
【问题描述】:
我正在学习 C,我正在尝试让一个玩具示例工作。我的假用例给出了一个字符串,其中每个 char 代表和 int,循环遍历字符串的每个 char 并将其转换为 int。到目前为止我尝试过的方法没有奏效。
编辑: 原始问题已编辑,现在包含 main(),以允许响应者根据 cmets 中的建议编译和使用 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
【问题讨论】:
-
如果您一次只想要一个字符,循环遍历字符串并从每个字符中减去
'0'应该可以工作。当然,您必须首先验证您的字符串都是以 10 个字符为基数 -
究竟是什么没有成功?
-
在我看来它工作正常
-
函数:
strlen()返回size_t而不是int, -
函数:
atoi()获取所有字符,从指定的地址开始,直到到达一个非数字字符,因此代码不是逐个字符而是逐步删除前导数字.此外,不应使用函数atoi()(通常),因为它没有给出成功/失败的指示。建议使用:strtol()