将 if 语句中的字符与 or 进行比较
Comparing chars in if statement with or
最近我在比较字符时遇到了问题。
#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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 布尔比较运算符是如何在C++中工作的
- C++将目录中的所有文件与::filesystem进行比较
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- shell排序中的交换和比较
- 如何在C++中比较两个char数组
- catch框架有没有办法比较流或文件
- 将 if 语句中的字符与 or 进行比较
- 将 OR 放入 if 语句会导致 ISO C++禁止指针和整数之间的比较(f 允许)
- 我是否正确地将枚举值与C++的"or"运算符进行比较?