while循环c ++中多个变量的条件

conditions for multiple variables in while loop c++

我试图让我的 while 循环显示 "Invalid input" 对于 3 个变量的 while 循环。 我刚开始使用 C++,所以我不是最擅长展示我需要的东西,但这是我的意思。

while(children1,children2,children3)<1||(children1,children2,children3)>100)
 cout << "invalid input"; return 0;

单独表达每个需求可能最简单:

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";

另请注意,如果您打算通过 whileiffor 等语句控制多条指令,则需要使用大括号将它们分组:

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);
}