array and structure

#include <iostream>
using namespace std;

const int SLEN = 20;
struct student {
    char fullname[SLEN];
    char hobby[SLEN];
    int ooplevel;
};

int getinfo(student pa[], int n)
{
    int total = 0;
    for(int i = 0; i < n; i++)
    {
        cout << "Enter your " << i + 1 << "#: ";
        if(!(cin >> pa[i].fullname >> pa[i].hobby >> pa[i].ooplevel))
        {
            cin.clear();
            while(cin.get() != '\n')
                continue;
            cout <<"Bad input!" << endl;
            break;
        }
        else total++;
    }
    return total;
}

void display1(student st)
{
    cout << "tradional way:"<<endl;
    cout << "student name: "<<st.fullname << endl;
    cout <<"student hobby: "<< st.hobby << endl;
    cout << "student level: "<< st.ooplevel << endl;
    cout << "------------------------------"<< endl;
}

void display2(const student *st)
{
    cout << "Use pointer:"<<endl;
    cout << "student name: "<<st-> fullname << endl;
    cout <<"student hobby: "<< st-> hobby << endl;
    cout << "student level: "<< st-> ooplevel << endl;
    cout << "------------------------------"<< endl;
}

void display3(const student pa[], int n)
{
    for(int i =0; i < n; i++)
    {
        cout << i+1 << "# student infomation: " << pa[i].fullname << endl;
        cout << "Hobby: " << pa[i].hobby << endl;
        cout << "Level: " << pa[i].ooplevel << endl;
        cout << "---------------------------------"<< endl;
    }
}

int main()
{
    cout << "Enter your class size: ";
    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<entered; i++)
    {
        display1(ptr_stu[i]);
        display2(&ptr_stu[i]);
    }
    display3(ptr_stu, entered);
    delete [] ptr_stu;
    cout << "Done!\n";
    return 0;
}

 

Here is the official key below:

int getinfo(student pa[], int n)
{
	int		num_array_elem = n;
	char	tmp[SLEN];
	for (unsigned i = 0; i < n; ++i) {
		cout << "Your name: ";
		cin.getline(tmp, SLEN);
		bool	blank_line = true;
		for (unsigned j = 0; j < strlen(tmp); ++j) {
			if (!isspace(tmp[j])) {
				blank_line = false;
				break;
			}
		}
		if (blank_line) {
			num_array_elem = i;
			break;
		}
		strcpy(pa[i].fullname, tmp);

		cout << "Hobby:";
		cin.getline(pa[i].hobby, SLEN);

		cout << "OOP score: ";
		cin >> pa[i].ooplevel;
		cin.get();
	}

	return (num_array_elem);
}

  

posted @ 2017-12-01 16:22  Bear_Guo  阅读(174)  评论(0编辑  收藏  举报