如何读取文本文件中的矩阵并将其存储在 C++ 中?

How can I read a matrix within a text file and storing it in c++?

我正在尝试通过读取名为 matrix.txt 的文件并存储它们的值来在 C++ 中构建一个矩阵,这样我就可以更轻松地 运行 我的其他算法。我对使用 fstream 很陌生,所以这可能不是最有效的代码,但这是我迄今为止的尝试(注意,大多数 类 用于其他算法)。

我决定进行测试,看看它是否工作正常。 但当我到达一行的末尾时,我似乎遇到了这个问题。 文本文件值由分隔符“,”分隔,但它的行由换行符分隔。 当我执行此代码时(底部有注释)我得到 2 个值。该行的最后一个值和下一行的第一个值。但是当我删除评论时,我没有遇到那个问题。 有办法解决这个问题吗?

我的代码:

    #include <iostream>
    #include <list>
    #include <math.h>
    #include <iomanip>
    #include <algorithm>
    #include <fstream>
    #include <string>
    using namespace std; 

int main(){
    string str[80][80];
    ifstream eulereightyone;
    int a = 0;
    int b = 0;
    eulereightyone.open("matrix.txt");
    if (!eulereightyone)
    {
        cout << "couldn't open file" << endl;
        system("pause");
        return 0;
    }
    while (eulereightyone.good())
    {
        getline(eulereightyone, str[a][b], ',');
        if (a > 78)
        {
            a = 0;
            ++b;    
        }
        a++;
    }
  //cout << str[78][1] << endl;
    cout << str[79][1] << endl;
  //cout << str[0][2] << endl;
    system("pause");
    return 0;
}

如果您这样做是为了学习如何使用静态表,这是可以接受的。 但是,如果您正在为一个更大的项目(或在获得一些 C++ 经验之后)处理您的数据,这不是一个好的做法,您绝对应该使用 标准库

您可能会经常得到这个答案,但最好不要在 C++ 中为 matrix/list/vectors/multimaps 重新编码容器。使用 标准库 这样您就不必重新实现所有排序 methods/templates 并且您将拥有有用的运算符,例如 move 用于非常大的子集数据.

这也是一个安全问题,如果您的代码使用静态表投入生产,您可能会发生溢出。

对于这个特殊问题,您可以执行 vector<string> 以便您的矩阵可以调整大小并由您定义,而不是静态的,如果您在定义的范围之外调用,将会正确失败。

vector<string> > vec;
const int rows = 80;
const int columns = 80;
vec.resize(rows * columns);
for (int row = 0; row < rows; ++row) {
    for (int col = 0; col < columns; ++col) {
        getline(eulereightyone, vec[row * columns + col], ',');
    }
}