【问题标题】:How do you have a user input values in an array using a function in C++?如何使用 C++ 中的函数在数组中输入用户值?
【发布时间】:2014-09-27 15:22:11
【问题描述】:

好的,我有这段代码可以让用户将数字输入到数组中,但希望将其变成一个函数。我是 C++ 新手,不确定如何去做。谁能给我一些提示或提示?我将不胜感激。代码如下:

main()
{
 int m;
 int n;
 int i;
 int j;
 int A[100][100];

 m = get_input ();
 n = get_input2 (); 

 cout << endl << "Enter positive integers for the elements of matrix A:" << endl;

 for (i = 0 ; i < m ; i++)
     for (j = 0 ; j < n ; j++)
         cin >> A[i][j];
return;
}

【问题讨论】:

  • 重点是你需要new数组的内存,而不是在堆栈上定义它,然后释放它。传入尺寸,返回newed 数据,然后在完成后调用delete[]。 (除非您还想传入分配的数组?在这种情况下,您也可以使用局部变量。)
  • 它必须是一个数组吗?在 C++ 中,惯用的方法是使用 std::vector。之后你打算用数组做什么?除了通过 [] [] 访问元素之外,您还需要做任何事情吗?通常最好避免在 C++ 中删除。

标签: c++ function multidimensional-array user-input


【解决方案1】:
void initialize(int x[][], int m, int n){
    cout << endl << "Enter positive integers for the elements of matrix A:" << endl;

    for (int i = 0 ; i < m ; i++)
       for (int j = 0 ; j < n ; j++)
       cin >> x[i][j];
}

main()
{
    int A[100][100],m,n;

   // m = get_input ();// you must have that method or cin>>m
    //n = get_input2 (); //you must have that method or cin>>n
     cout<<"Enter no of rows";
     cin>>m;
     cout<<"Enter no of columns";
     cin>>n;
    initialize (A,m,n);
    return;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2018-02-23
    • 1970-01-01
    相关资源
    最近更新 更多