根据命令行的输入创建一个2D数组

时间:2013-10-29 13:02:57

标签: c++

我需要从命令行获取整数个列和行作为输入。这就是我到目前为止所拥有的。我只是在我的数组中放入一些随机值来检查它是否正常工作

 14 int main(int argc, char *argv[])
 15 {
 16 
 17    int random_number;//used for random number
 18    int row, cols;//command line ARGUMENT VARIABLES
 19 
 20    //this section will create random numbers
 21    srand (time(NULL));
 22    random_number = rand() % 100;// 0 to 99
 23    cout << random_number << endl;
 24 
 25    //command line argument
 26    cout << "there are " << argc << " arguments." << endl;
 27    for (int narg = 0; narg < argc; narg++)
 28    {
 29       cout << narg << " " << argv[narg] << endl;
 30    }
 31 
 32    //this section is my array
 33    int print_array[2][2] = {{1,2}, {3,4}};
 34 
 35    for (int row = 0; row < 2; row++)
 36    {
 37       for(int column = 0; column < 2; column++)
 38       {
 39          cout << print_array[row][column] << " ";
 40       }
 41       cout << endl;
 42    }

1 个答案:

答案 0 :(得分:0)

如果您尝试使用命令行的输入创建2D数组,则需要使用动态内存(不是首选),或使用容器(例如std::vector):

int main(int argc, char** argv)
{
    if (argc != 3)
        exit(-1); // we are expecting exactly 3 arguments

    // unsigned because we cannot create negative sized arrays
    std::string sRows = std::string(argv[1]);
    std::string sCols = std::string(argv[2]);
    unsigned int rows = stoul(sRows); // get the first argument
    unsigned int cols = stoul(sCols); // get the second argument

    std::vector<std::vector<int>> print_array;

    // fill the vector here

    // now print the vectors
    std::for_each(print_array.begin(), print_array.end(), [&](const std::vector<int>& vec)
    {
        std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " ");
        std::cout << std::endl;
    });

    return 0;
}