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

#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语句中的条件满足时才会中断....但是即使在输入正确的输入后,循环也不会中断并且当我输入错误时输入,不允许我再次输入...

评论
  • yvero
    yvero 回复

    You need to print "success" before breaking out of the loop. Also, your check for !cin doesn't make sense. You could simplify this loop to:

    while ((cin >> len_password) && len_password > 15)
      cout << "Please enter an appropriate value:\n";
    
    cout << "success";
    

    The loop will keep executing until the user enters an appropriate value, and then "success" is printed outside the loop. This avoids any break statements within the loop.