我正在编写一段代码来检查用户输入的内容是否实际上是有效输入之一(在本例中为 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_of或 std::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/