【问题标题】:input text file into an 2d array in c将文本文件输入到c中的二维数组中
【发布时间】:2017-09-30 06:37:56
【问题描述】:
#include<stdlib.h>
#include<stdio.h>

int main() {

  FILE* file = fopen ("fourth.txt", "r");
  int i = 0;
  int rows=0;
  int rows2=0;
  int columns=0;
  int counter=0;
  int length=0;
  int multiply=0;

  fscanf (file, "%d", &i);
  rows=i;

  printf("the rows are %d\n", i);

  int matrix[rows][rows];
  length=rows*rows;

  if (rows<=0) {

      printf("error, this file cannot be processed");
      return 0;
  }

  do
  {
      if (fscanf(file, "%d", &i)==1) {

          if (counter<length) {

              matrix[rows2][columns]=i;
              counter++;
              columns++;

              if (columns==rows) {
                  rows2++;
                  columns=0;
              }
          }
          multiply=i;
      }
  } while (!feof(file));

  fclose (file);

  for ( int c = 0; c < rows; c++ ) {
      for ( int j = 0; j < rows; j++ ) {
          printf("matrix[%d][%d] = %d\n", c,j, matrix[c][j] );
       }
  }

  printf("the multiply is %d", multiply);

我正在尝试创建一个矩阵指数(换句话说,矩阵乘法)。然而,在我执行实际的数学过程之前,我必须从 txt 文件中读取数字作为输入并将它们存储在二维数组中。以上是到目前为止我从代码中获得的内容,但是,我很难将数字实际输入到数组中,因为当我在最后测试我的二维数组时,我得到了奇怪的结果。

例如: 1. 输入:

3
123
456
789
2

3 代表行数,这与这个特定二维数组的列数相同,因为矩阵是正方形的,意思是 所有行和列都相同。

2 代表指数,即我必须将原始矩阵与自身相乘的次数。

但是我的输出是

矩阵[0][0] = 123
矩阵[0][1] = 456,
矩阵[0][2] = 789
矩阵[1][0] = 2
矩阵[1][1] = 4214800
矩阵[1][2] = 0
矩阵[2][0] = 3
矩阵[2][1] = 0
矩阵[2][2] = 0

预期输出必须是:

123
456
789

在二维数组中

有什么原因吗?

另外,我将如何修改代码,因此无论 txt 文件中关于不同行和列的输入是什么,我仍然可以格式化正确的二维数组。谢谢

【问题讨论】:

  • 123 是一个数字 - 如果您想将其读取为 3 个数字 - 最好在它们之间添加空格 1 2 3
  • if (fscanf(file, "%d", &amp;i)==1) {(不包括负数时)--> if (fscanf(file, "%1d", &amp;i)==1) {
  • 注意:if (rows&lt;=0) {测试最好在int matrix[rows][rows];之前编码
  • do { if (fscanf(file, "%d", &amp;i)==1) { ... } while (!feof(file)); 处于非数字输入的无限循环中。
  • 要一次读取一个数字,使用"%d",使用fscanf(file, "%1d", &amp;i)(加1)

标签: c arrays matrix


【解决方案1】:

在您的输入文本文件中,一行中的数字不会以任何方式分隔。如果您需要多位数字,请考虑用空格或分号等符号分隔它们。

如果矩阵只有一位整数(即从 0 到 9 的数字),那就没问题了。

但如果一行中有 3 个数字,例如 21、13 和 4,那么在输入文件中它就是 21134

无法确定是 211,3,4 还是 21,1,34 还是 2,113,4 还是.......

在您的程序中使用fscanf(),每个%d 将读取整行,将其视为单个数字并将其分配给变量i

而不是先将大小读入i,然后将其复制到rows,就像

fscanf (file, "%d", &i);
rows=i;

你可以直接读入rows

fscanf( file, "%d", &rows);

并读取类似的值

for(rows2=0; rows2<rows; ++rows2)
{
    if( fscanf(file, "%1d%1d%1d", &matrix[rows2][0], &matrix[rows2][1], &matrix[rows2][2]) != 3)
    {
        perror("Error");
        break;
    }
}

然后在末尾读取multiply 的值

fscanf(file, "%d", &multiply);

您可以查看fscanf()的返回值来检查是否有错误发生。

您使用!feof(file) 检查文件结尾。知道的不多,看看here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 2010-09-26
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多