簡體   English   中英

如何使用 scanf 只讀取輸入中的數字?

[英]How can I read only numbers from an input with scanf?

實現一個 function,它接收一個整數數組及其容量,並用從鍵盤讀取的所有質數值填充數組,而不會溢出數組。 鍵盤輸入可能包含其他要忽略的數據(單詞)。 返回復制到數組中的元素數。 此外,提供足夠的 main()。

  #include <stdio.h>
    int fills(int arr[], int cap)

    {
    int element, flag=0,i=0,sec;
      while(scanf("%d", &element)==1 && i<cap)
        {
            printf("%d", element);
        sec=element;
       // printf("%d\n", sec);
          for(int j=2;j<sec/2;j++)
          {
              if(sec%j==0)
               flag=1;
          }
          if(flag==0)
          {
              arr[i]=element; 
              i++;
          }
        // printf("%d\n", arr[i-1]); 
         sec=0;
         
    }
    for(int k=0;k<i;k++)
    {
        printf("%d ", arr[k]);
    } 

}
   

     int main()
        {
            int arr[4], cap=4;
            fills(arr, cap);
            return 0;
        }

到目前為止,這是我的代碼,但我不能跳過單詞或其他元素

您可以從輸入中讀取字符串,檢測您讀取的字符串是否僅包含數字,然后決定如何處理它:是將字符串轉換為 integer,還是忽略它。

一個可靠的解決方案是在您嘗試讀取整數時忽略任何有問題的輸入。 例如:

/* read an integer value from fd ignoring any offending character
 * Parameters:
 * fd: FILE to read
 * err pointer to an integer which is set to 1 if a read error is encountered
 */
int getint(FILE* fd, int *err) {
    int i, cr;
    while ((cr = fscanf(fd, "%d", &i)) == 0) {   // can we read an int?
        if (fgetc(fd) == EOF) { // if no skip one character and test error condition
            if (err != NULL) {                   // set err if pointer is not NULL
                *err = 1;
            }
            return -1;                           // and return -1
        }
    }
    if (cr != 1) {                               // a possible fatal read error?
        if (err != NULL) {                       // same handling as above
            *err = 1;
        }
        return -1;
    }
    return i;                                    // Ok return the integer value
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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