【问题标题】:Store Matrix with integer from a text file into an array in c++将带有整数的矩阵从文本文件存储到c ++中的数组中
【发布时间】:2018-05-13 14:26:16
【问题描述】:

我有一个名为 matrices.txt 的文件,其中包含两个 3 x 3 的矩阵。 它们是:

1 2 3
4 5 6
7 8 9
1 2 3 
4 5 6 
7 8 9

我正在尝试从该文件中读取数据并将其存储到数组 proto_matrix 中,以便稍后将其拆分为两个矩阵。

我遇到的问题是我无法将数字存储在数组中。

我的代码是

#include <iostream>
#include <fstream>

using namespace std;

void main()
{
    int i = 0, j, k = 0, n, dimension;
    cout << "Enter the dimension of square matrices (3 by 3 would be 3) \n";
    cin >> n;
    dimension = n * n;
    int proto_matrix[2 * dimension];

    // make array of two matrices combined, this will be split into two matrices
    ifstream matrix_file("matrices.txt");

    while(matrix_file)
    {
        matrix_file >> proto_matrix[i];
    }
    matrix_file.close();
}

我尝试调试代码,似乎没有整数存储在数组中,只是随机数。

【问题讨论】:

  • int proto_matrix[2 * dimension]; 不是标准 C++;您必须为2 * dimensionints 动态分配足够的内存。
  • 在阅读之前务必确保文件is_open()
  • 试一试while(matrix_file &gt;&gt; proto_matrix[i];) { i++; }。您没有在读取时增加 i,因此读取的所有值(如果有)都进入了数组中的同一插槽,并且您想在计数之前测试读取是否成功。
  • 使用std::vector&lt;int&gt; proto_matrix(2 * dimensions); 而不是您正在使用的非标准 C++ 语法。
  • 顺便说一句,main 函数返回int。总是。

标签: c++ arrays file loops matrix


【解决方案1】:

这个:

int proto_matrix[2 * dimension];

是可变长度数组 (VLA),它不是标准 C++,但受某些编译器扩展支持。如果用g++ -pedantic main.cpp编译,肯定会报错。

这意味着如果您不得不使用数组,则需要动态分配内存。

你真的不知道,C++ 提供了std::vector,它可以相对容易地实现你想要的。我说的是相对的,因为你在一个文件中有两个矩阵,这使得解析文件有点棘手。通常我们将一个矩阵放在一个文件中,将另一个矩阵放在另一个文件中。

  • 二维数组可以表示为二维向量。
  • 您需要两个矩阵,因此需要两个二维向量。

因此,我将使用一个大小为 2(固定大小!)的数组,其中每个元素都将是一个 2D 向量。

此外,我将跟踪我现在正在从文件中读取哪个矩阵(第一个或第二个),以及我当前读取了多少行,以便填充矩阵的正确单元格。

index 将等于 0 或 1,以索引数组。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

int main()
{
    int i = 0, j, k = 0, n, dimension;
    cout << "Enter the dimension of square matrices (3 by 3 would be 3) \n";
    cin >> n;
    dimension = n * n;
    vector< vector<int> > v[2];
    v[0].resize(n);
    v[1].resize(n);
    // make array of two matrices combined, this will be split into two matrices
    ifstream matrix_file("matrices.txt");
    string line;
    int rows_read = 0, cols_read = 0, index = 0;
    while (std::getline(matrix_file, line))
    {
        std::istringstream iss(line);
        int a, b, c;
        if (!(iss >> a >> b >> c)) { break; } // error
        // process tuple (a, b, c)
        if(index == 0 && rows_read >= n)
        {
            rows_read = 0;
            index = 1;
        }
        //cout<<"rows = " << rows_read << " " << index<<endl;

        v[index][rows_read].push_back(a);
        v[index][rows_read].push_back(b);
        v[index][rows_read++].push_back(c);
    }
    matrix_file.close();

    for(int i = 0; i < 2; ++i)
    {
        cout << "Printing matrix " << i << endl;
        for(auto& matrix: v[i])
        {
            for(auto& number: matrix)
                cout << number << " ";
            cout << endl;
        }
    }
    return 0;
}

输出:

Printing matrix 0
1 2 3 
4 5 6 
7 8 9 
Printing matrix 1
1 2 3 
4 5 6 
7 8 9 

PS:与你的问题无关,而是What should main() return in C and C++?一个int

【讨论】:

    【解决方案2】:

    基于我的answer,我将在此处发布一个更简洁的示例,它实现了您的代码试图实现的目标:读取一维数据结构中的所有数字(稍后将以某种方式拆分为两个矩阵)。

    因此,对于这种情况,代码可以归结为:

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    #include <sstream>
    
    using namespace std;
    
    int main()
    {
        int i = 0, j, k = 0, n, dimension;
        cout << "Enter the dimension of square matrices (3 by 3 would be 3) \n";
        cin >> n;
        dimension = n * n;
        // make array of two matrices combined, this will be split into two matrices
        vector<int> proto_matrix;
        ifstream matrix_file("matrices.txt");
        string line;
        while (std::getline(matrix_file, line))
        {
            std::istringstream iss(line);
            int a, b, c;
            if (!(iss >> a >> b >> c)) { break; } // error
            proto_matrix.push_back(a);
            proto_matrix.push_back(b);
            proto_matrix.push_back(c);
        }
        matrix_file.close();
    
        for(auto& number: proto_matrix)
            cout << number << "\n";
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      您可以将所有值读入 flat 容器(例如 std::vector),然后再进行重新排列。下面的代码可能会给你一个思路:

      #include <vector>
      #include <fstream>
      #include <iostream>
      
      int main() {
        std::vector<int> values;
      
        std::ifstream fp("matrices.txt");
      
        for (int value; fp >> value; ) {
          values.emplace_back(value);
        }
      
        std::cout << "I read " << values.size() << " values:\n";
      
        for (auto && value : values) std::cout << value << " ";
      
        std::cout << "\n";
      }
      

      结果:

      $ clang++ matrixread.cpp -std=c++17
      $ ./a.out 
      I read 18 values:
      1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 
      

      【讨论】:

        【解决方案4】:

        您不会增加i,因此总是写入第一个元素。应该是:

        matrix_file >> proto_matrix[i++];
        

        【讨论】:

          猜你喜欢
          • 2013-03-13
          • 2021-03-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多