Char 类型和开关盒问题

问题描述 投票:0回答:1

我正在尝试做一个带有函数的计算器,我使用符号“+”“-”“/”“*”来选择操作,“x”来关闭程序,如果我插入任何其他值,程序会要求再次插入。但是如果我插入 x(多个,可能是误点击)字符,则 switch case 将执行 x 次。这是一个例子:As you can see the input is 'awd' and the switch has been executed with the 'a' the 'w' and the 'd'

你能帮我解决这个问题吗?我希望在这些情况下切换将被执行一次

我不知道如何解决它。 有些东西是用意大利语写的,但重要的东西是用英语写的。 这是脚本



#include <iostream>
#include <cmath>
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 o,s;
    
    cout << "*******************************Calcolatrice*******************************" << endl;
    
    do{
        s = 0;
        
         cout << "Enter the symbol corresponding to the operation you want to perform:" << endl << "'+' somma" << endl;
         cout << "'-' sottrazione " << endl <<"'*' moltiplicazione " << endl << "'/' divisione " << endl << "'x' per chiudere il programma " << endl;
            cin >> s;

         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;
}
c++ function char switch-statement
1个回答
0
投票

我可能会添加一个小功能,例如:

char read_one_of(std::string_view choices);`

读取输入字符,直到获得传递给它的选项之一,因此您可以这样称呼它:

s = read_one_of("+-/*x");

switch (x) { 
    // ...

这样,当您执行

switch
时,您就知道您获得的字符是有效的。

© www.soinside.com 2019 - 2024. All rights reserved.