C++ switch语句输入非数字字符时default分支无限循环问题求助
问题成因
该无限循环和switch本身没有关系,根源出在cin的输入错误处理逻辑上:
- 当使用
cin >> x读取int类型变量时,若输入的是字母这类不符合int格式的字符,cin会立刻进入失败状态,并将failbit置位。处于失败状态的cin会直接跳过后续所有输入操作,不会再等待用户输入。 - 输入错误的字符不会被从输入缓冲区中移除,会一直残留在缓冲区里。每次循环回到
cin >> x时,都会重复读取这个错误字符,重复触发输入失败,最终不断走default分支形成死循环。
修复方案
修复需要在每次输入后做错误检查,出现输入失败时主动重置流状态并清空残留的无效输入:
- 输入后先判断
cin是否处于失败状态 - 若失败,调用
cin.clear()重置流的错误标志位,恢复cin的正常工作状态 - 调用
cin.ignore()清空输入缓冲区中残留的所有无效字符,避免下次读取重复出错
修复后的完整代码如下:
#include <iostream> #include <string> #include <cmath> #include <unistd.h> #include <chrono> #include <thread> #include <fstream> #include <random> #include <time.h> // 新增头文件,用于获取输入流的最大长度 #include <limits> using namespace std; void sleepcp(int milliseconds) { clock_t time_end; time_end = clock() + milliseconds * CLOCKS_PER_SEC/1000; while (clock() < time_end) { } } int main() { START: int x; cout << "Enter a number: "; cin >> x; // 新增输入错误处理逻辑 if (cin.fail()) { // 重置流错误状态 cin.clear(); // 清空缓冲区所有残留字符,直到遇到换行符为止 cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Incorrect"<< endl; sleepcp(250); system("clear"); goto START; } switch (x) { case 1: cout << "Hi"<< endl; sleepcp(250); system("clear"); goto START; default: cout << "Incorrect"<< endl; sleepcp(250); system("clear"); goto START; } }
内容的提问来源于stack exchange,提问作者Diaz Michael
相关产品推荐
相关产品推荐

