在 if 语句中处理多个 or 的更优雅的方法是什么

What is a more elegant way of dealing with multiple or's in an if statment

本文关键字:是什么 方法 or 语句 if 处理      更新时间:2023-10-16

我有这样的代码来检查char数组中的每个char是否满足一定数量的属性:*是一个数字*或者是(+,-,*,/(

bool chkArray(char input[]) {
for (auto x = 0; x < strlen(input); x++) {
if (isdigit(input[x]) || input[x] == '+' || input[x] == '-' || input[x] == '*' || input[x] == '/' || input[x] == ' ') {
continue;
}
else {
return false;
}
}
return true;
}

我觉得有一种更优雅的方法来处理倍数或检查(+,-,*,/(。类似这样的东西:

bool chkArray(char input[]) {
for (auto x = 0; x < strlen(input); x++) {
if (isdigit(input[x]) || input[x] == '+', '-', '*', '/', ' ') {
continue;
}
else {
return false;
}
}
return true;
}

所以我现在想知道是否有人可以替代原始代码,使其更优雅?

由于c++14,最常用的方法可能是使用std::string文字和std::string::find()函数:

#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
using namespace std::literals::string_literals;
int main()
{
std::string input = "Hello world5!"s;
for(auto c : input) {
std::cout << std::boolalpha 
<< (std::isdigit(c) || "+-*/ "s.find(c) != std::string::npos) 
<< 'n';
}      
}

输出:

false
false
false
false
false
true
false
false
false
false
false
true
false

请参阅一个工作示例。

旧的解决方案是使用std::strchr:

if (isdigit(input[x]) || std::strchr("+-*/ ", input[x]))

Id建议创建一个函数,检查它是否是您想要的值之一,并让它返回布尔值类似的东西

bool Contains(char in)
{
return in=='+' || in =='-' || in == '*' || in == '/' || in== ' ';
}

尽管有更好的方法可以做到这一点,比如传递一个charecter数组进行检查,而不是硬编码。