一个函数中的不同数组

different arrays in one function

本文关键字:数组 函数 一个      更新时间:2023-10-16

我是 c++ 的初学者,我必须纠正一个函数,该函数要求用户输入五个不同数组的第一个元素的值。例如,学生姓名数组、学生 ID 数组等。这里的问题是这个函数的参数是什么。

这是我的尝试,我声明数组是全局的。我不知道错误在哪里。

const int SIZE=1000;
int studN[SIZE]; 
int id[SIZE]; 
string courseName[SIZE];
string courseSec[SIZE]; 
int regNom[SIZE];
void insertNew()
{ 
int index=0;
index++;
cout<<"Please enter the student name:  ";
cin>>studN[index];
cout<<"Please enter the student ID:  ";
cin>>id[index];
cout<<"Please enter the course name:  ";
cin>>courseName[index];
cout<<"Please enter the course section:  ";
cin>>courseSec[index];
cout<<"Please enter the registration number:  ";
cin>>regNom[index];
cout<<" Information stored"<<endl;
}

如果我理解正确,您想编写一个函数,该函数将使用给定索引设置数组元素的值。该函数可以如下所示

bool Insert( int studN[], int id[], string courseName[], string courseSec[], int regNom, size_t size, size_t pos )
{
    if ( size <= pos ) return false;
    cout << "Please enter the student name:  ";
    cin >> studN[pos];
    // other stuff
    // ,,,
    return true;
}

但无论如何,最好定义一个包含相应字段的结构或类数组。

由于已将数组声明为全局变量,因此无需为函数提供任何参数。

但是,索引应在函数外部初始化一次为 0。这是因为您不想在同一索引 = 1 处一次又一次地覆盖这些值。

此外,在每次int读取操作后,都应键入cin.ignore(),因为n字符驻留在输入缓冲区中,这会干扰进一步的字符串读取。

首先,

你需要一个main()函数来启动程序。这可能就是你想要的cin/cout所在的地方。

如果你想

隐藏变量,那么像你这样的变量并不是最佳的,所以把它们和你拥有的其余代码一起塞进主{}中

然后,您要将已添加到另一个函数的这些参数发送到另一个函数。喜欢

PrintStudents( int* studN, etc....) 
{
}

请注意,您需要使用指针。