簡體   English   中英

如何從 .t​​xt 文件中讀取整數並將它們存儲在 C 中的整數類型數組中

[英]How to read integers from .txt file and store them in a integer type array in C

我有一個文件,其中包含用' '分隔的整數

示例文件 1

8 7 8 8 7 7 7

示例文件2

10 0 3 11 0 2 3 3 2 4 5 6 2 11

我想讀取這些整數並將它們保存在一個整數數組中。

   -->int array[for example File1]={8,7,8,8,7,7,7}
   -->int array[for example File2]={10,0,3,11,0,2,3,3,2,4,5,6,2,11}

到目前為止我已經完成了這段代碼......有人可以幫忙嗎?

#include <stdio.h>
int main() {
  FILE *f1;
  int i,counter=0;
  char ch;
  f1 = fopen("C:\\Numbers.txt","r");

  while((ch = fgetc(f1))!=EOF){if(ch==' '){counter++; }}
  int arMain[counter+1];

  for(i=0; i<counter+1; i++) {
     fscanf(f1, "%d", &arMain[i]);
  }

  for(i = 0; i <= counter+1; i++) {
    printf("\n%d",arMain[i]);
  }

  return 0;
}

每次從文件中讀取內容時,指針都會移動一個位置。 在您讀取文件一次以計算整數的數量后,指針指向文件的末尾。

您必須倒回 FILE 指針,以便它返回到起點,您可以再次掃描以獲取數字。

#include <stdio.h>

int main(){
    FILE *f1;
    int i,counter=0;
    char ch;
    f1 = fopen("nums.txt","r");

    while((ch = fgetc(f1))!=EOF){if(ch==' '){counter++; }}
    int arMain[counter+1];

    rewind(f1); /* Rewind f1 */
    for(i=0; i<counter+1; i++)         {
        fscanf(f1, "%d", &arMain[i]);       
    }

    for(i = 0; i <= counter+1; i++)     {
        printf("\n%d",arMain[i]);       
    }

    return 0;

}

暫無
暫無

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

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