第一个函数getinfo(),一个结构体数组,一个int类型参数,结构体数组参数存储了学生的姓名,爱好,oop等级这三个信息,而int类型的参数则是输入数据的数目的上界,也可以通过直接敲回车来提前结束输入,否则就需要输入到上界数目个信息。
第二个函数display1(),该函数就只接受一个结构体参数,然后把结构体的内容显示出来。
第三个函数display2(),该函数接受一个结构指针,然后显示结构体内容。
第四个函数display3(),该函数接受结构体数组和int类型参数,对应于getinfo()函数的两个参数,然后把结构体的内容显示出来。
//arrobj.cpp -- functions with array objects
#include <iostream>
#include <array>
#include <string>
using namespace std;
const int SLEN = 30;
struct student {
char fullname[SLEN];
char hobby[SLEN];
int opplevel;
};
int getinfo(student po[], int num);
void display1(student po);
void display2(const student* po);
void display3(const student po[], int size);
int main() {
cout << "enter the class size:";
int class_size;
cin >> class_size;
while (cin.get() != '\n')
continue;
student* pt = new student[class_size];
int actual_size = getinfo(pt, class_size);
//cout << actual_size;
for (int i = 0; i < actual_size; i++) {
display1(pt[i]);
display2(&pt[i]);
}
display3(pt, actual_size);
delete[]pt;
cout << "Done!\n";
return 0;
}
int getinfo(student po[], int num) {
int i;
for (i = 0; i < num; i++) {
cout << "please enter the fullname of student(0 to quit):\n";
cin.getline(po[i].fullname, SLEN);
cout << "please enter the hobby of student:\n";
cin.getline(po[i].hobby, SLEN);
cout << "please enter the opplevel of student:\n";
cin >> po[i].opplevel;
cin.get();
}return i;
}
void display1(student po) {
cout << po.fullname << " " << po.hobby << " " << po.opplevel << endl;
}
void display2(const student* po) {
cout << po->fullname << " " << po->hobby << " " << po->opplevel << endl;
}
void display3(const student po[], int size) {
for (int i = 0; i < size; i++) {
cout << po[i].fullname << " " << po[i].hobby << " " << po[i].opplevel << endl;
}
}