从c++文件中获取输入(矩阵数组输入)

Getting input from a file C++ (Matrix Array Input)

本文关键字:输入 数组 文件 获取 c++      更新时间:2023-10-16

我将让用户输入一个包含如下数据的文件:

<>以前numRowsnumCols……x……x...…之前

现在我有麻烦从这样的文件读取数据。我不明白我应该怎么做才能从每行读取每个整数。这是我目前所看到的:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class my_exception : public std::exception {
    virtual const char *what() const throw() {
        return "Exception occurred!!";
    }
};
int main() {
    cout << "Enter the directory of the file: " << endl;
    string path;
    cin >> path;
    ifstream infile;
    cout << "You entered: " << path << endl;
    infile.open(path.c_str());
    string x;
    try
    {
        if (infile.fail()) {
            throw my_exception();
        }
        string line;
        while (!infile.eof())
        {
            getline(infile, line);
            cout << line << endl;
        }
    }
    catch (const exception& e)
    {
        cout << e.what() << endl;
    }
    system("pause");
    return 0;
}

我还想在每一行存储数据!这意味着在第一行之后,我想将数据存储到相应的变量和每个单元格值中。

我很困惑,我怎么能得到每个整数,并将它们存储在一个唯一的(numRows和numCols)变量?

我想将文件的前两行分别保存为numRowsnumCols,然后在每行之后的每个整数将是矩阵的一个单元格值。示例输入:

<>之前221 23 4之前

TIA

试试这个。第一行读取路径。然后,使用freopen将提供的文件与stdin关联。因此,现在我们可以直接使用cin操作,就像我们直接从stdin中读取一样,就像从文件中逐行输入到控制台一样。

在此之后,我创建了numRowsnumCols对应的两个变量,并创建了这个维度的矩阵。然后我创建一个嵌套的for循环来读取矩阵的每个值。

string path;
cin >> path;
freopen(path.c_str(),"r",stdin);
int numRows, numCols;
cin >> numRows >> numCols;
int matrix[numRows][numCols];   
for(int i = 0; i < numRows; i++){
    for(int j = 0; j < numCols; j++){
        cin >> matrix[i][j];
    }
}

或者你可以用它来创建你的矩阵

int** matrix = new int*[numRows];
for(int i = 0; i < numRows; i++)
    matrix[i] = new int[numCols];