簡體   English   中英

使用scanf將一串整數捕獲到C中的數組中

[英]Using scanf to capture a string of integers into an array in C

我試圖使用scanf捕獲一串數字並將其轉換為相應的數組。 例如,用戶將在1234中輸入,然后輸入,並將設置以下內容:

array[0]=1
array[1]=2
array[2]=3
array[3]=4

到目前為止,這是我的代碼:

    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*/);
}

我知道你必須讀取字符並將每個字符轉換為整數,但我不確定如何。

應該行

number = cardarray[i] - '0'; 

cardarray[i] = number - '0'; 

然后大衛說要計算答案

你在找atoi()

cardarray[i] = aoti(number);

http://www.codingunit.com/c-reference-stdlib-h-function-atoi-convert-a-string-to-an-integer

話雖這么說,你正在使用的方法是減去字符0的字符集值,如果你分配給正確的變量也可以正常工作:

cardarray[i] = number - '0';

我猜你想要:

printf("The number is %d\n",
   cardarray[0]*1000 + cardarray[1]*100 + cardarray[2]*10 + carrarray[3]);

您還可以使用:

printf("The number is %d%d%d%d\n",
    cardarray[0], cardarray[1], cardarray[2], cardarray[3]);

以下是一些代碼可能會有所幫助:

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM