[英]Input 12 digit number and save as int. C
I am new to C and memory allocation.我是 C 和 memory 分配的新手。 I am trying to take a 12 digit input and save as int so later on I can do some calculations.
我正在尝试输入 12 位数字并保存为 int,以便稍后我可以进行一些计算。 So far I have:
到目前为止,我有:
#include <stdio.h>
void main(void){
char number[12];
do
{
printf("Credit Card Number: ");
scanf("%lli", number);
} while (number == 1);
printf("%lli", number);
}
Right now I use long long int since I can use 64 bits, but when I run it and type in 123 I get:现在我使用 long long int 因为我可以使用 64 位,但是当我运行它并输入 123 时,我得到:
27583791809822484
Could someone explain what I am doing wrong, why the output is 27583791809822484 and if I have any styling errors.有人可以解释我做错了什么,为什么 output 是 27583791809822484 以及我是否有任何样式错误。
scanf %lli
expects a pointer to a long long int
. scanf %lli
需要一个指向long long int
的指针。 You provided a pointer to an array of 12 char.您提供了一个指向 12 个字符的数组的指针。
printf %lli
expects a long long int
. printf %lli
期望long long int
。 You provide a pointer.你提供一个指针。
long long int card_num;
scanf("%lli", &card_num);
printf("%lli", card_num);
If you wanted to portable code, you'd use如果你想移植代码,你会使用
#include <stdint.h>
#include <inttypes.h>
uint64_t card_num;
scanf("%" SCNu64, &card_num);
printf("%" PRIu64, card_num);
If you wanted to store the number as a string (which is quite reasonable for a credit card number), then char number[12]
makes sense, but you'd use %s
.如果您想将数字存储为字符串(这对于信用卡号来说非常合理),那么
char number[12]
是有意义的,但您会使用%s
。 Actually, it would have to be char number[13]
to be large enough to store 12 digits and the trailing NUL.实际上,它必须是
char number[13]
才能足够大以存储 12 位数字和尾随的 NUL。
char card_num[13];
scanf("%12s", card_num);
printf("%s", card_num);
#include <stdio.h>
void main(void){
long long int creditcard;
printf("Credit Card Number: ");
scanf("%lli", &creditcard);
printf("%lli", creditcard);
}
this will work.这会奏效。
EDIT: As stated in the comments, if you have leading zeros, this won't work.编辑:如评论中所述,如果您有前导零,这将不起作用。 Instead taking it as string like above is better.
取而代之的是像上面那样把它当作字符串更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.