c++ - 如何检查一个变量是否不等于 C++ 中的多个东西?

标签 c++ variables operators

我正在编写一段代码来检查用户输入的内容是否实际上是有效输入之一(在本例中为 1-9),如果不是,则会给出错误消息。

这是我的:

if (input != '1', '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' )
    {
      cout << "Error";
    }

但是好像不行。我以为我可以用逗号分隔它们,但也许我只是在想象。

唯一的选择就是:

input != '1' && input != '2' && input != '3' etc etc

我知道这个方法可行,但似乎有点啰嗦。有没有更简单的方法?

最佳答案

您可以将值存储在容器中并利用 std::find_if , std::none_ofstd::any_of功能:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<char> v = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
    char input = '1';
    if (std::none_of(v.cbegin(), v.cend(), [&input](char p){ return p == input; })) {
        std::cout << "None of the elements are equal to input.\n";
    } 
    else {
        std::cout << "Some of the elements are equal to input.\n";
    }
 }

关于c++ - 如何检查一个变量是否不等于 C++ 中的多个东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51631573/

相关文章:

c++ - 有哪些代码生成技术?

c++ - 编译错误 - Makefile 日志

java - 动态创建新变量或使用数组

c++ - 我已经重载<<和=运算符。为什么当我将一个对象分配给另一个对象并尝试打印该对象时,却打印出了垃圾邮件?

c++ - 将成员函数指针作为模板类型传递

php - 在类中访问 session 变量

PHP访问父类变量

python - 在处理 numpy 数组时,运算符 "numpy.dot()"、 "* "和 "@"之间有什么区别?

c++ - 模板,没有调用错误的匹配函数

c++ - g++:使用 ZIP 文件作为输入