如何从C++文件中读取矩阵

How to read in a matrix from a file in C++?

本文关键字:读取 文件 C++      更新时间:2023-10-16

>我试图从文件中读取n×n个矩阵,然后将该矩阵存储在一维数组中。我还想存储 n 的值。我已经研究了各种方法,但似乎无法将它们应用于我想要实现的目标。

这就是我到目前为止所拥有的,但我不确定该在 while 循环中放入什么。

/*READ IN THE IMAGE MATRIX FROM THE FILE*/
String lineA;
ifstream imFile;
imFile.open("imageMatrixDefined.txt");
if(imFile.fail()){
    cerr << "File cannot be found or opened" << endl;
    exit(1);
}
if(imFile.is_open(){
    cout << "file opened successfully!" << endl;
    while(!imFile.eof()){    
    }
}

输入文件可能如下所示:

1    2    3
2    3    1
3    3    2

其中制表符分隔元素。任何建议将不胜感激,因为我是C++新手。

数组具有固定大小。
在初始化数组之前,必须先获取 n 的值。

最好仔细检查是否要将该矩阵存储在一维数组或二维数组中。 如果是一维数组,检查矩阵在一维数组中的存储方式是好的。 有些存储它的第一行、第二行、...和第n行,有些存储它的第一列、第二列、...和第n列。

矩阵为 n × n,因此列数等于行数。
该文件一次存储一行。获取 n 的值并不困难。

while 循环

至关重要,但在 while 循环之前,获取 n 的值是解决问题的第一步。

当得到 n 的值时,数组很容易被初始化。您可以从 while 循环中的文件中逐一读取该行,使用分隔符作为制表符来获取每个矩阵元素,并将矩阵元素存储在数组中。

将 2D 数组读取到文件。假定输入以逗号分隔,每行一行,每行 x 列数,每列由制表符 (t) 字符分隔。不需要 EOL(行尾)选项卡,只需换行符 ( n )。请记住正确设置rowscolumns变量。测试代码是否正常工作。

using namespace std;
#include <iostream>
#include <fstream>
int main() {
  int rows=10, columns=10;
  ifstream f("input.txt");
  int input[rows][columns];
  for (int i=0; i<rows; i++){
    for (int j=0; j<columns; j++){
      f >> input[i][j];
    }
  }
  f.close();
  // Here you can add processing of the file, for example, print it:
  cout << "Input:" << endl;
  for (int i=0; i<rows; i++){
    for (int j=0; j<columns; j++){
      cout << input[i][j] << "  ";
    }
    cout << endl;
  }
  return 0;
}

您必须将自定义输入流与输入文件绑定。假设您的输入文件是"in.txt",它看起来与您指定的相同。

然后,以下代码从文件中读取,将其存储在一维数组中,并以矩阵形式打印生成的矩阵:

#include <iostream>
#include <fstream>
using namespace std;
int main () {
  ifstream myfile;
  myfile.open ("in.txt");
  cout << "Reading from a file.n";
  int arr[10];
  int k = 0;
  for (int i = 0; i < 3; ++i)
  {
    for (int j = 0; j < 3; ++j)
    {
        myfile >> arr[k];           //Read it in a 1D array   
        cout << arr[k] << "  ";
        ++k;
    }
    cout << "n";
  }
  myfile.close();
  return 0;
}

输出:

Reading from a file.
1  2  3  
2  3  1  
3  3  2