繁体   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