牛刀小试 - 练习结构体struct、字符串输入、文件写入

拓展学习

C++字符串的几种输入方法(string和字符数组)
结构体数组与结构体数组作为函数参数
结构体数组作为函数参数

/*********************************************************************
程序名: 实例:100 练习结构体struct、字符串输入、文件写入
说明:有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括学生号,姓名,三门课成绩),计算出平均成绩,
况原有的数据和计算出的平均分数存放在磁盘文件"stud"中。
*********************************************************************/
#include 
#include
#define NUM 5
using namespace std;

struct Student
{
	int number;
	char name[20];
	float Chinese, Math, English;
	float avg;
};

void DisPlayAvg(struct Student t[])
{
	for (int i = 0; i < NUM; i++)
	{
		cout << "name:" << t[i].name << endl;
		cout << "avg:" << t[i].avg << endl;
	}
}

void SaveStudent(struct Student t[])
{
	ofstream outfile("stud.txt", ios::app); // 以追加模式开启文件,如果不存在文件,则新建文件
	if (!outfile)
	{
		cerr << "Fail!\n";
	}
	else
	{
		for (int i = 0; i < NUM; i++)
		{
			outfile << "number:" << t[i].number <<
				"  name:" << t[i].name <<
				"  Chinese:" << t[i].Chinese <<
				"  Math:" << t[i].Math <<
				"  English:" << t[i].English <<
				"  avg:" << t[i].avg << endl;
		}

		cout << "写入文件stud成功!" << endl;
	}
}


int main() {
	Student stu[NUM];
	cout << "请输入五个学生的信息:顺序为学号,姓名,语,数,外\n例子:1 张三 80 92 78" << endl;
	for (int i = 0; i < NUM; i++)
	{
		cin >> (stu[i].number);
		cin.get();
		cin >> (stu[i].name);
		// cin.get(stu[i].name, 20);
		cin.get();
		cin >> (stu[i].Chinese);
		cin.get();
		cin >> (stu[i].Math);
		cin.get();
		cin >> (stu[i].English);
		(stu[i].avg) = (stu[i].Chinese + stu[i].Math + stu[i].English) / 3;
	}
	SaveStudent(stu);

	system("PAUSE");
	return 0;
}

你可能感兴趣的:(C++学习,c++)