简体   繁体   English

使用用户定义的尺寸在C ++中创建2D数组(正方形)?

[英]Creating a 2D array (square) in C++ with user defined dimension?

So I'm making a magic square program in C++, and the user has to input the dimensions of the square. 因此,我正在用C ++编写一个神奇的正方形程序,用户必须输入正方形的尺寸。 The input can only be odd numbers between the included bounds of 3 and 15. This is the code I have so far, which is not complete: 输入只能是3到15之间的奇数。这是我到目前为止的代码,尚不完整:

#include <iostream>
using namespace std;

int main() {

    int row = 0;
    cout << "Enter the size of a magic square: ";
    cin >> row;

    while (cin.fail() || row != 3, 5, 7, 9, 11, 13, 15)
    {
        cout << "Please enter an odd number within the bounds of 3 and 15.\n" << endl;
        cout << "Enter the size of a magic square: ";
        cin >> row;
    }

    if (row = 3, 5, 7, 9, 11, 13, 15) {

        int** square = new int*[row];

        for (int i = 0; i < row; i++)
        {
            square[i]= new int[row];
        }

        cout << "Magic Square #1 is:" << endl;
    }

    cin.get();
    return 0;
}

I'm having a lot of issues. 我有很多问题。 First off, how do you make a 2D array which has user defined dimensions? 首先,如何制作具有用户定义尺寸的2D阵列? Since the array will be a square, I tried 由于阵列将是一个正方形,我尝试

int** square = new int*[row][row];

but I was told that the second dimension had to be a constant, which I don't understand why. 但有人告诉我第二维必须是一个常数,我不明白为什么。 Also, my error checking for user input isn't functioning as intended. 另外,我对用户输入的错误检查未按预期运行。 If you enter a non-integer, the error message endlessly loops. 如果输入非整数,错误消息将无限循环。 But then, if you put in any integer, the message will take the input, but then reprompt the user to make enter an integer again, with no end. 但是,如果您输入任何整数,则消息将接受输入,但随后会提示用户再次输入一个无尽的整数。

Can anyone help me out? 谁能帮我吗? I just started with C++, and my only background is in Java. 我刚开始使用C ++,而我的唯一背景是Java。 Thank you. 谢谢。

As MushroomBoy suggested, you can create a 2-dimensional matrix using vector . 正如MushroomBoy建议的那样,您可以使用vector创建二维矩阵。 Here's how the code will look for a 2D square matrix: 这是代码查找2D方阵的方式:

#include <iostream>
#include <vector>

using namespace std;

int main() {

  int row = 0;
  cout << "Enter the size of a magic square: ";
  cin >> row;

  while (cin.fail() || row < 3 || row > 15 || (row % 2) == 0)
  {
    cout << "Please enter an odd number within the bounds of 3 and 15.\n" << endl;
    cout << "Enter the size of a magic square: ";
    cin >> row;
  }

  vector< vector<int> > square_matrix(row, vector<int>(row));
  // Do something with vector...

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM