用户指定的二维数组大小

时间:2018-11-21 04:40:30

标签: c++ arrays multidimensional-array

因此,当我提示用户输入数字时,我有一个代码,我希望根据用户输入的内容来更改2D数组的大小,例如:

输入1到12之间的数字:
3

然后2D阵列将根据该大小而变化,成为3x3 2D阵列,希望我能说得尽可能清楚,如果有人可以引导我找到解决方案,我将不胜感激,谢谢大家! !

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>

using namespace std;

double Atemp = 0;
double Utemp = 0;
double Working = 0;
double Total = 0;
char Answer = 'x';
int Umain;



void displayOverview ();

void playOrQuit();

void promptNumber();

void fillUserArray(char grid[]);

int main(){

    displayOverview();

    playOrQuit();

    promptNumber();


    return 0;
}

void displayOverview(){

   }

void playOrQuit(){

    string playOrNot;

    cout << "If you want to play please press 'p' for play, and 'q' if you wish to quit\n";
    cin >> playOrNot;

    if(playOrNot == "p"){
        cout << "Awesome, lets start playing !!! \n";

    }if(playOrNot == "q"){
        cout << "Alright then, see you soon !!\n";
        exit(0);
    }if(playOrNot != "p" && playOrNot != "q"){
        cout << "Invalid entry !!\n";
        exit(0);
    }
}


void promptNumber(){

    do{
    cout << "Please Enter numbers between 1 and 12: ";
    cin >> Umain;
    if(Umain <= 12){
            for (Utemp = Umain; Utemp > 0; Utemp--){
            cout << "Please enter a number: ";
            cin >> Atemp;
        }
        }else{
            cout << "Not within limit :(\n";
        }
    }while (Answer == 'y');
}

void fillUserGrid (char grid[]){

    for( int row = 0; row < Umain; row++ ) {
        for(int col = 0; col < Umain; col++){
            grid[row][col] = userInput.at( row * Umain + col );
        }
    }
}

void outputUserGrid(char grid[]){

    for (int row = 0; row < Umain; row++){
        for(int col = 0; col < Umain; col++){
              cout << grid[row][col]<<" ";
        }
    cout << endl;
  }
}

1 个答案:

答案 0 :(得分:2)

在您的游戏中仅使用12x12阵列是非常合法的。如果用户想在较小的网格上玩游戏,则可以只使用其中的一部分。

这可能是唯一的问题,如果您遇到了对性能至关重要的程序的L1 / L2缓存问题,或者您要存储大量此类网格并需要减少内存使用量。如果这些情况中的任何一种适用于您,我都会感到惊讶。