简体   繁体   中英

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. For example, a user would enter in 1234, then enter, and the following would be set:

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()

cardarray[i] = aoti(number);

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:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM