将 if 语句中的字符与 or 进行比较

Comparing chars in if statement with or

本文关键字:or 比较 字符 if 语句      更新时间:2023-10-16

最近我在比较字符时遇到了问题。

#include <iostream>
#include <string>
using namespace std;
int main()
{
string test1 = "test";
string test2 = "adssadad";
if (test1[0] == 'b' || 'd')
{
cout << "it equals" << "n";
}
return 0;
}

每次我比较 if 语句中的字符和 or 出现时 - if 语句总是返回 true 并且执行里面的代码。我该如何解决此类问题?

if (test1[0] == 'b' || 'd')

相当于

if ((test1[0] == 'b') || 'd')

由于==的优先级高于||。这始终计算为true,因为'd'隐式计算为true

可能你认为这意味着什么

if (test1[0] == ('b' || 'd'))

但这也行不通,因为这将评估为

if (test1[0] == true) // <=> if (test1[0])

无论何时test[0] != ''都是如此.您需要的是分别测试每个案例

if ((test1[0] == 'b') || (test1[0] == 'd'))

如果有很多值要检查,那么将它们存储在容器中并使用算法可能会更容易。

const std::vector<char> vals {'b', 'd'};
if (std::find(vals.cbegin(), vals.cend(), test1[0]) != vals.cend())

'd' 的计算结果为非零,这在 C++ 中被解释为true。即使 OR 的一个操作数为真,则整个表达式为真,因此执行cout行。

你想写test[0] == 'b' || test[0] == 'd'

你的 if 语句解释如下:if [(test1[0] == 'b') || ('d')]由于"d"不是空或零,因此它的计算结果始终为 true。 将语句更改为if (test1[0] == 'b' || test1[0] = 'd')

在此处使用开关:

switch(test[10])
{
case b:
case d:
cout << "it equals" << "n";
break;
}