簡體   English   中英

讀取文件,然后將數字存儲在數組C中

[英]Read a file then store numbers in array C

所以我有一個名為“ score.txt”的文件,其中包含內容

NAME
20
NAME2
2

而且我正在使用此代碼,但是會出現錯誤,而且我不知道如何將文件中的整數放入數組中。

int main(){

FILE* file = fopen ("score.txt", "r");
 int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
{  
  printf ("%d ", i);
  fscanf (file, "%d", &i);      
}
  fclose (file);
 system("pause");
 }  

我只是自我學習,我已經嘗試了2個小時了

使用fscanf進行輸入(其中某些行格式失敗)的問題是, while循環的每次迭代都不會推進文件,因此會卡住。

您可以通過使用fgets來獲取數據並使用sscanf來獲取數字來獲取解決方案:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(void) {
    int i = 0;
    int ret = 0;
    char buf[50];

    FILE *file = fopen("score.txt", "r");
    if (file == NULL) {
         fprintf(stderr,"Unable to open file\n");
         exit(1);
    }

    while (fgets(buf,sizeof(buf),file)) {
         ret = sscanf(buf,"%d",&i);
         if (ret == 1) { // we expect only one match
               printf("%d\n", i);
         } else if (errno != 0) {
               perror("sscanf:");
               break;
         }
     }
     fclose(file)
     return(0);
}

這將輸出,供您輸入:

20
2    

我們檢查sscanf的輸出,因為它告訴我們格式是否正確匹配,這只會在帶有整數的行上發生,而不會在“ NAME”行上發生。 我們還會檢查“ errno”,如果sscanf遇到錯誤,它將設置為非零。

我們使用了char buf[50]; 聲明一個具有50個插槽的char數組,然后fgets將其用於存儲該行的讀數; 但是,如果該行的長度超過50個字符,則fgets將以50個字符塊讀取該行,並且您可能無法獲得所需的結果。

如果希望將讀取的整數存儲到數組中,則必須聲明一個數組,然后在每次讀取時在該數組中分配一個插槽給讀取的int值,即int_array[j] = i (其中j將隨您使用的每個插槽而變化)。 我將其保留為練習以實現此目的。

暫無
暫無

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

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