1

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




}
3
  • This question needs clarification. If each line corresponds to a player, why ask the user for the number of players ? How is it that you're extracting just the numbers from the input file ? I see no parsing / tokenizing ? Commented Oct 2, 2017 at 2:59
  • @user501138, no need to know the number of players. What I want to know is if there is any way I can store the equation into an array where I can manipulate the numbers using pointers? Commented Oct 2, 2017 at 3:04
  • Why are you issuing a delete [] arr when arr is not dynamically allocated using new[]? Also, this has more to do with trying to convert the string "1x+1y+1z=5" and strings looking like this into an array with 4 elements. This has virtually nothing to do with file reading. Commented Oct 2, 2017 at 3:07

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

if i am in your position, i will first tokenize every line you get in the file and slice up every number. then i will store it in the array (dont forget to cast every number to integer.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.