【问题标题】:Reading a two columned file in C在 C 中读取一个两列文件
【发布时间】:2018-04-03 00:07:38
【问题描述】:

我有如下两列文件:

9 9
1 2
3 2

我正在尝试使用fscanf 读取它并将我的int * buff 作为格式。

FILE *fp = fopen(argv[1], "r");
int num_rows = 0;
int num_columns = 2;
int i = 0;
int j = 0;

int *buff = calloc(10, num_columns * sizeof(int));

我遇到的问题是我不知道为fscanf(fp, %d %d\n, idk1, idk2) 放置什么

我想将它们放在buff 中,但我不知道在哪个位置。

for(i = 0; i < num_columns; i++) {
    for(j = 0; j <= num_rows; j++){
        int line = fscanf(fp, "%d %d\n", &buff[num_columns], &buff[num_rows]);
        if(line == EOF){
            break;
        }
        if(num_rows % 10 == 0){
            num_rows += 10;
            buff = realloc(buff, num_rows * num_columns * sizeof(int));
        }
    }
}

我正在读取我认为是相同位置的值,但我没有看到相同的输出。

for(i = 0; i < num_rows; i++){
  for(j = 0; j < num_columns; j++){
      printf("%d", buff[i * num_columns + j]);
  }
  printf("\n");
}

我认为这是输出:

92
20
00
00
00
...
...

但它应该只匹配输入文件:]

9 9
1 2
3 2

我应该在fscanf 内放置什么位置,以便稍后在memarray[i * num_columns + j]; 内打印相同的数据?

【问题讨论】:

  • memarray 是什么?请发帖minimal reproducible example!不是 COMPLETE 的重要部分。请提供一个预期输出的例子,我不明白你想要什么。
  • 为什么不使用ij?我看到了其他一些问题:您在哪里将num_rows 设置为 0 以外的值?您首先遍历列,然后遍历行,但文件一次读取一行,因此可能应该切换这两个 for 构造。

标签: c pointers memory-management


【解决方案1】:

我认为您要存储的是每一行。在您的代码中 fscanf(fp, "%d %d\n", &amp;buff[num_columns], &amp;buff[num_rows]) 是错误的。您应该使用索引ij 的某些表达式,而不是使用num_rowsnum_columns。基本上,您在 buff[num_columns]buff[num_rows] 上写过价值。

您想逐行读取文件,那么您只能使用单循环来完成。循环for(j = 0; j &lt;= num_rows; j++) 并尝试使用fscanf(fp, "%d %d\n", &amp;buff[ num_rows*num_columns ], &amp;buff[ num_rows * num_columns + 1 ] ) 存储。

我也不知道你为什么使用num_rows += 10; 它会干扰你的循环索引。如果要为 10 个新行分配内存,只需在 realloc(buff, num_rows * num_columns * sizeof(int)) 中提供 num_rows*10 而不是 num_rows

【讨论】:

    猜你喜欢
    • 2015-07-22
    • 2020-06-11
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    相关资源
    最近更新 更多