Dany Dany - 3 years ago 130
C++ Question

Storing data into a multidimensional array

I could use some help. I am trying to read from a file. the file contains this:

1x+1y+1z=5
2x+3y+5z=8
4x+0y+5z=2


I want to store this into a two dimensional array. Rows are 3 and columns will always be 4. I only want to store the integer values, in this case that will be 1 1 1 5 2 3 5 8 4 0 5 2. How can I store this values into the array? This is what I tried to doing but it is not working. Thank you for the help.

int main(){

fstream file;


file.open("matrix.txt", ios::in);



int arr[3][4];


// copy integers into array and display
for (int i = 0; i < 3; i++){
for(int j= 0; j < 4; j++){
file >> arr[i][j];
cout << arr[i][j];
}
}




}

Answer Source

You need first to extract numbers from each equation and then store them in the array. I will show you how to extract these numbers and the rest is trivial I guess.

#include <iostream>
#include <string>
using namespace std;


void getNumbers(string str, int&x, int&y, int& z)
{
    string X, Y, Z;

    size_t idx = str.find("x");
    size_t idy = str.find("y");
    size_t idz = str.find("z");

    X = str.substr(0, idx);
    Y = str.substr(idx+1, idy-(idx+1));
    Z = str.substr(idy+1, idz-(idy+1));

    x = stoi(X);
    y = stoi(Y);
    z = stoi(Z);
}

int main()
{
    string line("2x+82y-12z=5");

    int x(0), y(0), z(0);
    getNumbers(line,x,y,z);
    cout << line << endl;
    cout << x << "  " << y << "  " << z << endl;
    return 0;
}

The result is

2x+82y-12z=5
2  82  -12
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download