简体   繁体   English

如何从 .t​​xt 文件中读取整数并将它们存储在 C 中的整数类型数组中

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

I have a file that contains integers separated with ' '我有一个文件,其中包含用' '分隔的整数

Example File1示例文件 1

8 7 8 8 7 7 7

Example file2示例文件2

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

I want to read these integers and save them in an integer array.我想读取这些整数并将它们保存在一个整数数组中。

   -->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}

I have done this code so far... Can anyone help here?到目前为止我已经完成了这段代码......有人可以帮忙吗?

#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;
}

Each time you read something from a file, the pointer moves one position.每次从文件中读取内容时,指针都会移动一个位置。 After you've read the file once to count the number of integers, the pointer is pointing to the end of the file.在您读取文件一次以计算整数的数量后,指针指向文件的末尾。

You have to rewind your FILE pointer, so it goes back to the start and you can scan again to get the numbers.您必须倒回 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.

相关问题 从.txt文件中读取数字并将它们存储在C中的数组中 - Read numbers from a .txt file and store them in array in C 如何使用C从.txt文件的特定点读取整数? - How to read integers from a specific point of a .txt file using C? 如何在C中读取输入文件并将整数存储到数组中 - How to read input file and store integers into array in C 如何在 C 中读取 .txt 文件并将数字存储到二维数组中 - How to read a .txt file in C and store the numbers into a 2D array 如何读取txt文件并存储在c中的结构数组中 - how to read txt file and store in structure array in c C语言帮助:如何将.txt文件中的字符串存储到字符数组中? 从命令行参数btw读取此.txt文件。 - C language help:How to store strings from a .txt file into a character array? This .txt file is read from a command line argument btw. 如何从非结构化的.txt文件中读取单词并将每个单词存储在C中的char数组中? - How to read words from unstructured .txt file and store each word in a char array in C? 从.txt文件获取整数并在c中对它们执行操作 - Getting integers from .txt file and perfoming actions on them in c 如何在.txt文件C中搜索特定的字符串和整数并使用它们? - How to search for specific strings and integers in a .txt file C and use them? 如何一次从文件中读取 16 个字节并将它们存储到数组中 - How to read 16 bytes from a file at a time and store them into an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM