函数:函数操作结构体通过按值传递以及按址传递,使用动态内存
struct student{
char fullname[SLEN];
char hobby[SLEN];
short age;
};
使用动态内存创建此结构数组,使用函数进行输入,输出,显示的操作。
#include <iostream>
const size_t SLEN = 30;
struct student{
char fullname[SLEN];
char hobby[SLEN];
short age;
};
size_t getinfo(student pa[], const size_t n);
void display1(student st);
void display2(const student *ps);
void display3(const student pa[], size_t n);
int main(void)
{
using std::cin;
using std::cout;
cout << "Enter class size: ";
size_t class_size;
cin >> class_size;
while(cin.get() not_eq'\n') continue;
student *ptr_stu=new student[class_size];
size_t entered = getinfo(ptr_stu, class_size);
for(size_t i=0; i<entered; i++)
{
display1(ptr_stu[i]);
display2(&ptr_stu[i]);
}
display3(ptr_stu, entered);
cout << "Done\n";
delete []ptr_stu;
return 0;
}
size_t getinfo(student pa[],const size_t n)
{
using std::cin;
using std::cout;
size_t i=0;
cout << "Input datas to array(EOF to quit)\n";
while((cin.eof()not_eq true) and (i < n))
{
student temp;
cout << "Enter the student name:";
cin.getline(temp.fullname, SLEN);
cout << "Enter the student hobby:";
cin.getline(temp.hobby, SLEN);
cout << "Enter the student age:";
cin >> temp.age; cin.get();
if(not cin.eof())
{
pa[i++]=temp;
cout << "\nnext";
}
}
return i;
}
void display1(student st)
{
std::cout << "\nstudent_name:" << st.fullname << std::endl
<< "student_hobby:" <<st.hobby << std::endl
<< "student_age:" <<st.age << std::endl;
}
void display2(const student *ps)
{
std::cout << "\nstudent_name:" << ps->fullname << std::endl
<< "student_hobby:" << ps->hobby << std::endl
<< "student_age:" << ps->age << std::endl;
}
void display3(const student pa[], size_t n)
{
for(size_t i=0; i<n; i++)
{
std::cout << "\nstudent_name:" << pa[i].fullname <<std::endl
<< "student_hobby:" << pa[i].hobby <<std::endl
<< "student_age:" << pa[i].age <<std::endl;
}
}
posted on 2017-10-31 20:38 MACHINE_001 阅读(140) 评论(0) 编辑 收藏 举报