我需要从C中的stdin输入一个4位数输入,如1234,并将数字分别存储为1,2,3,4。我怎么能这样做?
答案 0 :(得分:1)
将其作为字符串(char*
)阅读。伪代码
char str[MaxLen];
Input str;
possibly do some checking that the input string is in required format.
int a0 = str[0] - '0';
int a1 = str[1] - '0';
etc.
答案 1 :(得分:1)
您可以使用:
int no, i=0, a[4];
scanf("%d", &no);
while(i<4)
{
a[i]=no%10;
no /= 10;
i++;
}
答案 2 :(得分:1)
您可以使用getchar:
int a[4],c,i;
for (i=0;i<4;i++) {
while (!isdigit(c=getchar()));
a[i]=c-'0';
}
答案 3 :(得分:0)
这个怎么样?
void separate_digits(int four_digits, int *outarray)
{
for (int i = 0; i < 4; ++i) {
outarray[i] = four_digits % 10;
four_digits = four_digits / 10;
}
}
确保outarray足够大!
答案 4 :(得分:0)
试试这段代码:
char input[100];
// we know that every digit is less than 10, so a full int isn't necessary
int8_t output[100];
// set all values to -1
memset(output, -1, sizeof(output));
scanf("%99s", &input);
int len = (int) strlen(input);
for (int i = 0; i < len; i++) {
// assuming input is in ASCII
output[i] = input[i] - '0';
}
for (int i = 0; i < 100; i++) {
if (output[i] == -1)
{
break;
}
printf("%i, ", output[i]);
}
最多输入100个字符,并输出每个字符的各个数字。