[英]Using scanf to capture a string of integers into an array in C
I am trying to use scanf to capture a string of numbers and convert it into a corresponding array. 我试图使用scanf捕获一串数字并将其转换为相应的数组。 For example, a user would enter in 1234, then enter, and the following would be set: 例如,用户将在1234中输入,然后输入,并将设置以下内容:
array[0]=1
array[1]=2
array[2]=3
array[3]=4
Here is my code so far: 到目前为止,这是我的代码:
void user_input()
{
int cardarray[16];
int i;
char number;
printf("Enter in the number:");
for (i=0; i<16; i++)
{
scanf("%c", &number);
number = cardarray[i] - '0';
}
printf("The number is %d\n", /*some value*/);
}
I know you have to read characters and convert each into an integer digit, but I'm not exactly sure how. 我知道你必须读取字符并将每个字符转换为整数,但我不确定如何。
Should the line 应该行
number = cardarray[i] - '0';
read 读
cardarray[i] = number - '0';
Then does as David says to compute the answer 然后大卫说要计算答案
You're looking for atoi()
你在找atoi()
cardarray[i] = aoti(number);
http://www.codingunit.com/c-reference-stdlib-h-function-atoi-convert-a-string-to-an-integer http://www.codingunit.com/c-reference-stdlib-h-function-atoi-convert-a-string-to-an-integer
That being said, the method you're using which is to subtract the charset value of the character 0
will also work fine if you assign to the right variable: 话虽这么说,你正在使用的方法是减去字符0
的字符集值,如果你分配给正确的变量也可以正常工作:
cardarray[i] = number - '0';
I'm guessing you want: 我猜你想要:
printf("The number is %d\n",
cardarray[0]*1000 + cardarray[1]*100 + cardarray[2]*10 + carrarray[3]);
You can also use: 您还可以使用:
printf("The number is %d%d%d%d\n",
cardarray[0], cardarray[1], cardarray[2], cardarray[3]);
Here is some code may be helpful: 以下是一些代码可能会有所帮助:
#include <stdio.h>
int main(void)
{
int i = 0;
/* firstly, capture the input */
scanf("%d", &i);
/* secondly , extract for each number:
1234 -> 4,3,2,1
*/
int ia[256] = {0};
int len = 0;
while(i){
ia[len++] = i%10;
i /= 10;
}
/* thirdly, reverse the array */
int j = 0;
while(j < len-j-1){
int t = ia[j];
ia[j] = ia[len-j-1];
ia[len-j-1] = t;
j++;
}
/*let's see if it works */
for (j=0; j < len; j++){
printf("%d ", ia[j]);
}
putchar('\n');
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.