簡體   English   中英

將文本文件輸入到c中的2d數組中

[英]input text file into an 2d array in c

#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文件中讀取數字作為輸入並將其存儲在2d數組中。 以上是到目前為止我從代碼中獲得的信息,但是,我很難將數字實際輸入到數組中,因為當我在最后測試2d數組時,我得到的結果很奇怪。

例如:1.輸入:

3
123
456
789
2

3表示行數,與該特定2d數組的列數相同,這是因為矩陣是正方形的,這意味着所有行和列都相同。

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文件中關於不同行和列的輸入是什么,我仍然可以格式化適當的2d數組。 謝謝

在輸入文本文件中,一行中的數字不會以任何方式分開。 如果需要多位數字,請考慮使用空格或分號之類的符號將其分開。

如果矩陣只有一位整數(即從0到9的數字),那就很好了。

但是如果一行中的3個數字分別是21134和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)檢查文件結尾。 我不太了解,但在這里看看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM