问题:
解答:
#include <iostream>
using namespace std;
const int SLEN = 30;
typedef struct _Student
{
char fullname[SLEN];
char hobby[SLEN];
int ooplevel;
}Student;
int getinfo(Student pa[], int len)
{
int i = 0;
for (i = 0; i < len; i++)
{
cout << "请输入第" << i + 1 << "个学生的姓名:";
cin >> pa[i].fullname;
cout << "请输入第" << i + 1 << "个学生的爱好:";
cin >> pa[i].hobby;
cout << "请输入第" << i + 1 << "个学生的水平:";
cin >> pa[i].ooplevel;
if (!cin)
{
cin.clear();
while (cin.get() != '\n')continue;
cout << "输入有误,程序终止!" << endl;
break;
}
}
return i;
}
void display1(Student st)
{
cout << "学生的姓名为:" << st.fullname << endl;
cout << "学生的爱好为:" << st.hobby << endl;
cout << "学生的水平为:" << st.ooplevel << endl;
}
void display2(const Student* ps)
{
cout << "学生的姓名为:" << ps->fullname << endl;
cout << "学生的爱好为:" << ps->hobby<< endl;
cout << "学生的水平为:" << ps->ooplevel << endl;
}
void display3(const Student pa[], int n)
{
for (int i = 0; i < n; i++)
{
cout <<"第" <<i+1<< "位学生的姓名为:" << pa[i].fullname << endl;
cout << "第" << i+1 << "位学生的爱好为:" << pa[i].hobby << endl;
cout << "第" << i+1<< "位学生的水平为:" << pa[i].ooplevel<< endl;
}
}
int main()
{
cout << "请输入班级人数:";
int class_size;
cin >> class_size;
while (cin.get() != '\n')continue;
Student* ptr_stu = new Student[class_size];
int entered = getinfo(ptr_stu, class_size);
for (int i = 0; i < class_size; i++)
{
display1(ptr_stu[i]);
display2(&ptr_stu[i]);
}
display3(ptr_stu, entered);
delete[]ptr_stu;
cout << "Done\n";
return 0;
}
运行结果:
考查点:
- 结构体指针作为函数参数
- 结构体数组作为函数参数
2024年8月31日20:39:17