如何进行while循环但有更多条件C++
cout << "Options:n1: Change Namen2: Change Passwordn3: Change Addressn4: Withrawn5: DepositnL: Log outn>";
while (user_input2 != '1' && user_input2 != '2' && user_input2 != '3' && user_input2 != '4' && user_input2 != '5' && user_input2 != 'L')
{
cout << "Invalid input";
}
那么我该如何缩短 while 条件呢?
我试着做:
cout << "Options:n1: Change Namen2: Change Passwordn3: Change Addressn4: Withrawn5: DepositnL: Log outn>";
while (user_input2 != '1','2','3','4','5','L')
{
cout << "Invalid input";
}
但它不起作用。
编辑1:“我为我想做的事情添加了更多提示”
回答
您可以对to的范围使用<and>运算符,但您必须明确处理以下检查:'1''5''L'
while (user_input2 != 'L' && (user_input2 < '1' || user_input2 > '5'))
{
cout << "Invalid input";
}
- @Patrick — character encodings aren’t really involved here. In C++ and C the digits `[‘0’ .. ‘9’]` are required to be contiguous and increasing. So that test is valid for every character encoding that the compiler supports.