c++class

Passing in a file name to a constructor


I'm trying to build a constructor that takes a file name as an argument, opens and reads the file, but when I run my code I'm always getting Error:

file could not open

Here's a short version of my code (I'm very new to this, so please take that into account):

#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"));
}

Solution

  • It seems to be that you put the file in a different directory from where the code is running or that the name of the file is not exactly "m2.txt". If you put the file in side of its own folder in the correct directory you would have to enter the name as "FolderName\\m2.txt" where "FolderName" is the name of the folder you put the file in.