在 if 语句中处理多个 or 的更优雅的方法是什么
What is a more elegant way of dealing with multiple or's in an if statment
我有这样的代码来检查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数组进行检查,而不是硬编码。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 通过JNI传递数据数组的最快方法是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 在C++中包含原型文件的正确方法是什么?
- 在 OpenCV C++ 中估计基本矩阵之前对相应点进行归一化的正确方法是什么?
- 在PostgreSQL中根据它们的ID选择大量行的最快方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 将一系列整数放入类的最佳方法是什么?
- 从长整整转换为uint64_t的推荐方法是什么?
- C++:使用方法调用析构函数的顺序是什么?
- 将此布尔值传递给此函数的最有效方法是什么?