C++计算器char类型与switch case多字符重复执行问题求助
问题描述
我正在制作一个带函数的计算器,使用+、-、/、*选择运算,x用于关闭程序。若输入其他值,程序会要求重新输入,但输入多个字符时,switch语句会执行对应次数。例如输入awd,switch会分别对a、w、d执行逻辑。希望解决该问题,使多字符输入时switch仅执行一次。
解决方案
问题根源是cin >> s只会读取输入的第一个字符,剩下的字符会留在输入缓冲区里,下一次循环时会被直接读取,导致switch多次执行。下面提供两种解决方式:
方法1:清空输入缓冲区
这是最直接的修复方式,在读取字符s之后,立即清空输入缓冲区里的所有残留内容(直到换行符):
cin.ignore(numeric_limits<streamsize>::max(), '\n');
需要额外包含<limits>头文件,否则numeric_limits无法使用。这样不管输入多少字符,只会处理第一个,剩下的都会被丢弃,不会影响下一次循环。
方法2:读取整行输入做验证
这种方式更严谨,直接拒绝多字符输入:
- 将变量
s的类型从char改为string - 使用
getline(cin, s)读取整行输入 - 先判断输入长度是否为1,再检查字符是否是有效运算符或
x,不符合要求则直接提示错误,不进入switch逻辑。
修改后的代码(方法1)
#include <iostream> #include <cmath> #include <limits> // 必须包含此头文件 using namespace std; float somma(float a, float b); float sottrazione(float a,float b); float moltiplicazione(float a,float b); float divisione(float a,float b); int main(){ setlocale(LC_ALL,"ita"); float a,b; char s; cout << "*******************************Calcolatrice*******************************" << endl; do{ s = 0; cout << "Enter the symbol corresponding to the operation you want to perform:" << endl << "'+' somma" << endl << "'-' sottrazione " << endl << "'*' moltiplicazione " << endl << "'/' divisione " << endl << "'x' per chiudere il programma " << endl; cin >> s; // 清空输入缓冲区,丢弃所有剩余字符直到换行 cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << " S: " << s << endl; switch(s){ case '+': cout << "Inserire il numero 1: "; cin >> a; cout << "Inserire il numero 2: "; cin >> b; somma(a,b); break; case '-': cout << "Inserire il numero 1: "; cin >> a; cout << "Inserire il numero 2: "; cin >> b; sottrazione(a,b); break; case '*': cout << "Inserire il numero 1: "; cin >> a; cout << "Inserire il numero 2: "; cin >> b; moltiplicazione(a,b); break; case '/': cout << "Inserire il numero 1: "; cin >> a; cout << "Inserire il numero 2: "; cin >> b; divisione(a,b); break; case 'x': case 'X': break; default: cout << "No operator has been chosen. Try again!"; s = 0; break; } cout << endl << endl; }while(s != 'x' && s!= 'X'); cout << "**************************************************************************"; return 0; } float somma(float a, float b){ float x = a+b; cout << x; return x; } float sottrazione(float a, float b){ float x = a-b; cout << x; return x; } float moltiplicazione(float a, float b){ float x = a*b; cout << x; return x; } float divisione(float a, float b){ float x = a/b; cout << x; return x; }
内容的提问来源于stack exchange,提问作者Gianluca Mennella
相关产品推荐
相关产品推荐

