好的,我已经学习 C++ 大约 4 天了,它是我的第一门编程语言。所以这真正意味着我只有大约 8 个小时的编程经验,其中很多是阅读我的 C++ 书籍的介绍并弄清楚如何使用 XCode。
无论如何,我的初学者 C++ 书要求我执行以下操作:“编写一个密码提示,只为用户提供一定次数的密码输入尝试,以便用户无法轻松编写密码破解程序。”
唯一的问题是我刚刚学习了循环,我认为这本书还没有涵盖如何限制尝试次数。谁能帮忙?我看过this ,但它对我来说太先进了,我不明白。这是代码:(真正基本的新手代码...抱歉,如果它侮辱了你的智慧)
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string username;
string password;
while ( 1 )
{
cout << "Enter your username: " << endl;
cin >> username;
cout << "Enter your password: " << endl;
cin >> password;
if ( username != "billy" && password != "bob" )
{
cout << "Incorrect username/password combination. Please try again." << "\n" <<
endl;
}
else
{
break;
}
}
cout << "Access granted." << endl;
}
最佳答案
while ( 1 ) { }
构造将 {}
中的任何内容重复到无穷大,除非您明确地从循环中break
。顺便说一下,这是一个循环。
你怎么能在多次尝试后摆脱它?你可以有一个计数器,它随着每次尝试而递增,并在达到极限时从循环中跳出:
if ( ++counter >= limit )
break;
或者简单地将条件移动到 while 中
while ( ++counter < limit )
或使用简单的 for
循环或 do {} while()
。
关于c++ - 在 C++ 中限制登录尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15234021/