我试图让我的while循环显示"输入无效"对于3个变量的while循环。 我刚刚开始使用c ++,所以我不是最好的尝试显示我需要的东西,但这里是我的意思。
while(children1,children2,children3)<1||(children1,children2,children3)>100)
cout << "invalid input"; return 0;
答案 0 :(得分:4)
分开表达每项要求可能最容易:
while (children1 < 1 || children2 < 1 || children3 < 1 ||
children1 > 100 || children2 > 100 || children3 > 100)
std::cout << "invalid input\n";
C ++ 11的替代方案是:
#include <algorithm>
...
while (std::min({ children1, children2, children3 }) < 1 ||
std::max({ children1, children2, children3 }) > 100)
std::cout << "invalid input\n";
FWIW,如果您将数字保持在std::vector
另一个 - 可以说更优雅 - 选项可用:
std::vector<int> children;
children.push_back(23);
children.push_back(123);
children.push_back(13);
// ...however many you like...
while (std::any_of(std::begin(children), std::end(children),
[](int n) { return n < 1 || n > 100; }))
std::cout << "invalid input\n";
另请注意,如果您希望多条指令由while
,if
或for
等语句控制,则需要使用大括号对其进行分组:
int retries_available = 3;
while (std::any_of(std::begin(children), std::end(children),
[](int n) { return n < 1 || n > 100; }))
{
std::cout << "invalid input\n";
if (retries_available-- == 0)
return 0;
get_new_values_for(children);
}