Abhishek Ghosh
Abhishek Ghosh

Reputation: 2706

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

I will have user input a file which will contain some data like this :

numRows
numCols
x x x ... x 
x x x ... x
.
..
...

Now I am having trouble reading data from a file like this. I am not understanding what should I do to read each integer from each line. This is what I have so far:

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

Also what I want is to store data at each line! That means after the first line I want to store data into the corresponding variable and each cell value.

I am confused as to how can I get each integer and store them in a unique(numRows and numCols) variable?

I want to save first two lines of the file into numRows and numCols respectively, then after each line's each integer will be a cell value of the matrix. Sample input :

2
2
1 2 
3 4

TIA

Upvotes: 1

Views: 1544

Answers (1)

Banach Tarski
Banach Tarski

Reputation: 1829

Try this out. The first line reads in the path. Then, using freopen we associate the file provided with stdin. So now we can directly use cin operations as if we are directly reading from stdin and as if the input from the file is typed line for line into the console.

Following this, I create two variables corresponding to numRows and numCols and create a matrix of this dimension. Then I create a nested for loop to read in each value of the matrix.

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];
    }
}

Alternatively you can use this to create your matrix

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

See this for more reference.

Upvotes: 1

Related Questions