在比较C++中的字符时,有没有特殊的语法

Is there special syntax to follow when comparing chars in C++?

本文关键字:有没有 语法 字符 比较 C++      更新时间:2023-10-16

我一直在学习C++,并尝试创建一个基本的计算器应用程序。目标是从用户那里获得0-9中的两个数字,以及一个数学运算(+,-,*,/);如果键入了其他字符,我希望循环该程序以不断提示正确的输入。

但每当我运行程序时,它都无法识别数字0-9,并不断重复循环。这是我正在使用的3个主要功能。从主要方面来说,我只是给他们打电话,所以我怀疑问题是否存在。请帮忙?

哦,我知道我永远不应该使用go to,但我想要练习。如果你能指出更有效的编写代码的方法,那就太棒了。非常感谢。

int GetUserInput(){
    using namespace std;
    cout << "Please enter a number between 0-9." << endl;
    
    char inputChar; 
    cin >> inputChar;
    while (inputChar != ('1' || '2' || '3' || '4' || '5' || '6' || '7' || '8' || '9' || '0')) {
        cout << "Please enter a number between 0-9." << endl;
        cin >> inputChar;
    }
    return static_cast <int> (inputChar);
}
char GetMathematicalOperation(){
    using namespace std;
    cout << "Please enter a mathematical operator (+, -, *, /)" << endl;
    // Storing user input character into char inputChar
    char inputChar; 
    
    inputloop:
    cin >> inputChar;
    switch(inputChar) {
        case('+'):
        case('-'):
        case('*'):
        case('/'):
            break;
        default:
            cout << "Please enter a mathematical operator (+, -, *, /)" << endl;
            goto inputloop;
        }
    return inputChar;
}
int CalculateResult(int x, char Operator, int y){
    if (Operator = '+')
        return x+y;
    if (Operator = '-')
        return x-y;
    if (Operator = '*')
        return x*y;
    if (Operator = '/')
        return x/y;
    return 0;
}

||运算符需要对布尔表达式进行操作,而哪些字符不是。您需要将其扩展到while (inputChar != '1' && inputChar != '2' && ...

或者,您可以利用数字的字符代码是连续的这一事实。换句话说,你可以做while (inputChar < '0' || inputChar > '9')

此外,在CalculateResult函数中,您需要将这些=更改为==,否则,您将覆盖Operator变量,而不是与之进行比较。

在C++中

('1' || '2' || '3' || '4' || '5' || '6' || '7' || '8' || '9' || '0') == true

更具体地,当与==!=运算符相比较时,具有不是特定0(值,而不是字符)的值的char评估为true

所以你的表情

inputChar != ('1' || '2' || '3' || '4' || '5' || '6' || '7' || '8' || '9' || '0')

相当于

inputChar != true

最好将所有这些chars放入一个容器中,并检查容器中是否存在用户输入。

未测试代码

char mychars[] = {'1','2','3','4','5','6','7','8','9','0'};
std::set<char> inputChars;
inputChars.insert(mychars, mychars+10);
if(inputChars.find(inputChar) != inputChars.end())
{
...
}

您也可以使用isdigit来执行以下操作:

while(!isdigit(inputChar)) {  
    // code here  
}  

另一个解决方案:if (std::string("0123456789").find(inputChar) != std::string::npos)。变量npos-无位置-表示未找到。

您想检查inputChar是否在"0"到"9"的范围之外,所以您需要这样的东西:

while (inputChar < '0' || inputChar > '9') 

您的条件是错误的。。。您需要检查(inputchar!='0')&amp;(inputchar!='1')&amp&amp;(inputchar!='9')

while (inputChar != ('1' || '2' || '3' || '4' || '5' || '6' || '7' || '8' || '9' || '0'))

你必须与每个角色进行比较。

while ((inputChar != '1') ||  (inputChar != '2') ....

或者简单地说-

while ((inputChar < 47) || (inputChar > 57))

接下来,

if (Operator = '+')

编译器本应向您发出警告。这是一项任务。如果要进行比较,实际上需要==运算符。

相关文章: