#include<string>
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
//定义结构体生日
typedef struct birthday {
int year=0000, month=00, day=00;
}Birthday;
//定义结构体学生
struct Student {
string name="NULL";
int id=0, list_id=0;
Birthday birthday;
}stu[100];
Student* p = stu;
int i = 0; //作为已录入信息个数的判断符
bool IsOver = false;
void setStuMes();
bool checkInput();
void welcomeText();
bool switchInput();
void checkStuMes();
void getBirthday(int i);
//主函数
int main() {
while (!IsOver) {
welcomeText();
IsOver = switchInput();
}
}
//记录学生信息
void setStuMes() {
char temp;
for (; i < 100; i++) {
do {
cout << "请输入姓名:";
cin >> (p + i)->name;
} while (!checkInput());
do {
cout << "请输入学号:";
cin >> (p + i)->id;
} while (!checkInput());
do {
cout << "请输入生日(以空格为间隔):";
cin >> (p + i)->birthday.year >> (p + i)->birthday.month >> (p + i)->birthday.day;
} while (!checkInput());
(p + i)->list_id = i + 1;
cout << "信息已录入!是否继续?(y/n):";
for (;;) {
cin >> temp;
if (temp == 'y')
break;
else if (temp == 'n')
return;
else
cout << "输入有误!请重新输入:";
}
}
}
//检查输入是否正确
bool checkInput() {
if (cin.fail()) {
cout << "输入数据有误!请重新输入!" << endl;
cin.clear();
cin.sync();
return false;
}
else
return true;
}
//欢迎信息
void welcomeText() {
printf("===========================\n");
printf("|欢迎进入学生信息录入系统!|\n");
printf("|1----------------录入信息|\n");
printf("|2----------查询已录入信息|\n");
printf("|0--------------------退出|\n");
printf("===========================\n");
}
//根据用户输入选择分支
bool switchInput() {
int x;
do {
cout << "请输入:";
cin >> x;
} while (!checkInput());
switch (x) {
case 1:setStuMes(); break;
case 2:checkStuMes(); break;
case 0: {
cout << "已退出程序!" << endl;
return true;
}; break;
default: {
cout << "输入有误!请重新输入!" << endl;
checkInput();
}; break;
}
return false;
}
//输出已录入信息
void checkStuMes() {
int j = 0;
if (i == 0) {
cout << "没有任何已录入数据!" << endl;
return;
}
for (; j <= i; j++) {
cout << endl;
cout << "ID:" << (p + j)->list_id << endl;
cout << "姓名:" << (p + j)->name << endl;
cout << "学号:" << (p + j)->id << endl;
getBirthday(j);
cout << endl;
}
}
//获得生日信息
void getBirthday(int i) {
cout << (p + i)->birthday.year << "-" << (p + i)->birthday.month << "-" << (p + i)->birthday.day << endl;
}
当给switchInput中的变量x输入字符时会陷入死循环 用了很多方法也没排除问题
已经尝试用cin.fail()做判断并用checkInput重置错误但是没有效果