将文件名传递给构造函数

问题描述 投票:0回答:1

我正在尝试构建一个构造函数,该构造函数将文件名作为参数,打开并读取文件,但是当我运行代码时,我总是收到错误:文件无法打开,这是我的代码的简短版本(我对此很陌生,所以请考虑到这一点)

#include <vector>
#include <string>
#include <stdexcept>
#include <iostream>

using namespace std;

class Matrix {
public:
    Matrix(int rows, int cols);                      
    Matrix(string filename);                                
private:
    int nRows;                                     
    int nCols;   
    vector<float> data;                             
};

Matrix::Matrix(string filename) {
    ifstream file;
    file.open(filename);
    if (!file) 
        throw runtime_error("Error: Could not open file.");
    file >> nRows >> nCols; 
    data.resize(nRows * nCols);
    for (int i = 0; i < nRows * nCols; ++i) 
        file >> data[i]; 
    if (!file) 
        throw runtime_error("Error: File format incorrect.");
}

int main() {

  Matrix m2(string("m2.txt"));
}
c++ class
1个回答
0
投票

似乎您将该文件放在与代码运行位置不同的目录中,或者该文件的名称不完全是“m2.txt”。如果您将文件放在正确目录中其自己的文件夹中,则必须输入名称“FolderName\m2.txt”,其中“FolderName”是您放置文件的文件夹的名称。

© www.soinside.com 2019 - 2024. All rights reserved.