mardi 28 juin 2016

Generating a random 2D array


I want to make a simple program where a user can input "i x y" where x and y are integers, dimensions of the array. I have made a class myarray which makes the matrix. However the output of the program is blank spaces and n. Does anyone know what can I do to fix it?

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

class myarray
{
    char** grid;
    int dimX,dimY;
public:
    myarray(){grid=0;}
    myarray(int m,int n) {grid = new char* [m]; for(int i=0;i<m;i++) {grid[i]=new char [n];} dimX=m; dimY=n;}
    ~myarray(){for(int i = 0; i < dimX; ++i) {delete[] grid[i];} delete[] grid;}
    char** fetcharray(){return grid;}

    void display_grid();
    void randomize_grid(){for(int i=0;i<dimX;i++) for(int j=0;j<dimY;j++) grid[i][j]=rand()%10;}
};

int main()
{
    srand(time(NULL));
    bool check(true);
    while(check)
    {
        char a; //a-firstinp;
        int m,n; //m,n-grid size
        cin>>a;

        switch(a)
        {
        case 'i':
        case 'I': {cin>>m>>n;
                  myarray c(m,n);
                  c.randomize_grid();
                  c.display_grid();
                  break;}
        default: {cout<<"Invalid input! Possible commands: i,c,l,v,h,k,f,s,x! Try again: n";
                  break;}
        }
    }
}

void myarray::display_grid()
{
    for(int i=0;i<dimX;i++)
    {
        cout<<"n";
        for(int j=0;j<dimY;j++)
            cout<<grid[i][j];
    }
}

Thank you in advance!


Aucun commentaire:

Enregistrer un commentaire