为什么循环没有中断,并且 if 条件没有按预期工作?
Why the loop is not breaking and also the if condition isnt working as expected?
#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
语句。
相关文章:
- C++ 在条件未按预期工作时执行
- 唤醒多个线程以在每个条件下工作一次
- 为什么循环没有中断,并且 if 条件没有按预期工作?
- 当循环在条件C++之前停止工作时
- 如何正确地编写这些条件,以便它们在控制台中工作
- 如何编写一个通用函数,该通用函数在没有任何条件和条件的情况下工作(无论是真实和错误)
- if(x & y) 条件在 c++ 中的工作原理
- C++ 条件变量通知未按预期工作
- 逗号(,)在条件部分中两个表达式之间的for循环中的工作方式
- Boost::线程 / C++11 std::thread,想要唤醒工作线程的条件
- C++条件运算符在全局函数中使用时无法正常工作
- C++11:条件变量只工作一次
- 我在这里滥用了指针吗?虽然循环条件似乎无法正常工作
- 没有条件值的 FOR 循环"for (int i = 1; ; i++)"无法正常工作
- boost::timed_wait中的Notify条件变量只工作一次
- std::find条件语句未按预期工作
- Boost:等待工作线程等待条件变量
- ||操作员在while条件下未按预期工作
- 条件/三元运算符是如何工作的?c++
- c++条件是正确的,但不工作