在比较C ++中的字符时是否有特殊的语法?

时间:2013-07-18 20:52:54

标签: c++ character-properties

我一直在学习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;

}

7 个答案:

答案 0 :(得分:1)

在C ++中

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

更具体地说,与char0相比,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()) { ... } 放入容器中,并检查容器中是否存在用户输入。

未经测试的代码

{{1}}

答案 1 :(得分:1)

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

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

另外,在CalculateResult函数中,您需要将=更改为== - 否则,您将覆盖Operator变量,而不是与之进行比较。< / p>

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

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

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

或者只是 -

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

接下来,

if (Operator = '+')

编译器应该给你警告。这是一项任务。如果您打算进行比较,实际上您需要==运算符。

答案 5 :(得分:0)

您的情况有误...您需要检查(inputchar!='0')&amp;&amp; (inputchar!='1')&amp;&amp; ...&amp;&amp; (inputchar!='9')

答案 6 :(得分:0)

另一种解决方案:if (std::string("0123456789").find(inputChar) != std::string::npos)。变量npos - 没有位置 - 意味着找不到。