如何使用C++中的函数在数组中使用用户输入值?

问题描述:

好的,所以我有这个代码让用户输入数字到一个数组中,但是想把它变成一个函数。我是C++新手,不确定如何去做。任何人都可以给我一些提示或提示吗?我将不胜感激。代码如下:如何使用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; 
} 
+1

主要的一点是你需要'new'为数组的内存,而不是把它定义在堆栈上,然后再释放它之后。传入维度后,返回新数据,然后在完成时调用delete []'。 (除非你还想传递分配的数组吗?在这种情况下,你也可以使用局部变量。) – Rup 2014-09-27 15:25:47

+0

它是否必须是特定的数组?在C++中,这样做的惯用方法是使用std :: vector。你打算在数组之后做什么?除[] []的访问元素外,您还需要做其他任何事情吗?避免在C++中删除通常会更好。 – 2014-09-27 15:29:08

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; 
}