为什么循环没有中断,并且 if 条件没有按预期工作?

Why the loop is not breaking and also the if condition isnt working as expected?

本文关键字:工作 条件 并且 循环 中断 为什么 if      更新时间:2023-10-16
#include"std_lib_facilities.h"
int main()
{
int i = 0;
int len_password;
cout<<"How Long Should Be Your Password?n";
while(i == 0){
cin>>len_password;
if(!cin && len_password > 15){
cout<<"Please enter an appropriate value:n";
}
else{
break;
cout<<"success!";
}
}
}

我希望这段代码在循环中断时打印成功......并且只有当满足 if 语句中的条件时,循环才会中断。但即使在输入正确的输入后,循环也不会中断,而且当我输入错误的输入时,它不允许我再次输入......

如果您检查它小于 15,则打印应该在中断之前,并且您不需要 !cin

在脱离循环之前,您需要打印"成功"。此外,您的!cin检查没有意义。

相反,您可以检查cin操作是否失败,如果是,则可以清除流以获取其他输入:

while(!(std::cin >> len_password) || len_password > 15)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::cout << "Please enter an appropriate value:n";
}
cout << "success";

循环将继续执行,直到用户输入适当的值,然后在循环外部打印"成功"。这样可以避免循环中的任何break语句。