【问题标题】:How to read integers from .txt file and store them in a integer type array in C如何从 .t​​xt 文件中读取整数并将它们存储在 C 中的整数类型数组中
【发布时间】:2017-10-25 14:46:18
【问题描述】:

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

示例文件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;
}

【问题讨论】:

  • 您需要rewind。和&lt;= --> &lt;, char -->。 int.
  • 您需要正确格式化您的 C 代码。例如像你的 C 教科书中的示例。
  • @BLUEPIXY 当你说 char --> int 你的意思是 char ch; (这是唯一包含字符的行)谢谢
  • 顺便说一句,在不计算字节的情况下计算数字,使用如下代码:int dummy; while (fscanf(f1, "%d", &amp;dummy) == 1) counter++; - 此代码检查来自 fscanf 的返回代码,成功读取数字后将为 1。这将自动删除空格,不易出现the EOF bug,并正确处理两位数。
  • ^这个!因为它以与读取元素相同的方式计算元素。计算它们之间的空格只能是一种估计;如果使用其他类型的空格来分隔数据,或者值之间有多个空格字符,则会失败。它摆脱了程序中实际数字计数为count + 1 的愚蠢符号。

标签: c file scanf fopen


【解决方案1】:

每次从文件中读取内容时,指针都会移动一个位置。在您读取文件一次以计算整数数量后,指针指向文件末尾。

你必须倒回你的 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;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-15
    • 2014-08-14
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多