我正在尝试将一个 long long 整数转换为字符串数组,其中 1 的列位于数组的位置 0,10 的列位于位置 1,100 的列位于位置 2,如下所示:
输入:4444555566667777 -----> 输出:[4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7]
为了测试我的代码,我为最后一行编写了 printf("%d\n",number_str[3])
。我希望我的程序输出位置 4 的值“7”。相反,它输出“52”。如我所料,将我的最后一行更改为 printf("%d\n",number_str[4])
会产生“53”而不是“6”。任何人都可以解释发生了什么事吗?
当然 52 和 53 对应于 ASCII 值,但是,我怎样才能将它们转换为整数呢?我可以排队吗?
我的程序的这一部分的目的是将 10、1,000、100,000、10,000,000...列中的所有数字相加。以 10 为基数的信用卡号码中每隔一个数字。这是我尝试进行 Luhn 验证的第一步。
// Libraries
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Program
int main(void)
{
// Get CC number
printf("Enter your credit card number: ");
long long number_ll = GetLongLong();
// printf("%lld\n", number_ll);
// Convert long long to string
char number_str[64];
sprintf(number_str, "%lld", number_ll);
// printf("%s\n", number_str);
// Get length of card number string
int cclength = strlen(number_str);
// Check the length of card number string
if ( ! (cclength == 13 || cclength == 15 || cclength == 16))
printf("INVALID\n");
else
printf("%d\n",number_str[3]);
最佳答案
要将 ascii 转换为整数,请使用
#include <stdlib.h>
int atoi(const char *str);
改变这个
printf("%d\n",number_str[3]);
到
char buf[2];
buf[0]=number_str[3];
buf[1]='\0';
printf("%d\n",atoi((const char*)buf));
关于使用字符串数组调用整数的 1's, 10' s, 100's... 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21212391/