C++判断用于switch分支的变量有误 但陷入死循环

#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重置错误但是没有效果

cin输入接收的是字符数组,而不是int,你需要将输入强转成int,不然永远不会进入switch语句 所以一直返回alse

在输入语句前面加一行代码,清除缓存

fflush(stdin);

您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!

速戳参与调研>>>https://t.csdnimg.cn/Kf0y

C和C++完整教程:https://blog.csdn.net/it_xiangqiang/category_10581430.html