在C中输入一个不带空格的整数数组

如何在没有空格的情况下输入一个大数字(一个即使在long int中也无法存储的数字)?我们需要整数数组中的这个大数字,这样每个数组元素都存储一个数字。

null
Input : 10000000000000000000000000000000000000000000000
We need to read it in an arr[] = {1, 0, 0...., 0}

在C scanf()中,我们可以指定一次读取的位数。这里我们只需要一次读取一个数字,所以我们使用%1d。

// C program to read a large number digit by digit
#include <stdio.h>
int main()
{
// array to store digits
int a[100000];
int i, number_of_digits;
scanf ( "%d" , &number_of_digits);
for (i = 0; i < number_of_digits; i++) {
// %1d reads a single digit
scanf ( "%1d" , &a[i]);
}
for (i = 0; i < number_of_digits; i++)
printf ( "%d " , a[i]);
return 0;
}


输入:

27
123456789123456789123456789

输出:

1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 

我们也可以使用上面的样式来读取任意数量的固定数字。例如,下面的代码以3位为一组读取大量数字。

// C program to read a large number digit by digit
#include <stdio.h>
int main()
{
// array to store digits
int a[100000];
int i, count;
scanf ( "%d" , &count);
for (i = 0; i < count; i++) {
// %1d reads a single digit
scanf ( "%3d" , &a[i]);
}
for (i = 0; i < count; i++)
printf ( "%d " , a[i]);
return 0;
}


输入:

9
123456789123456789123456789

输出:

123 456 789 123 456 789 123 456 789 

当我们使用 fscanf()

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享