【发布时间】:2021-01-19 21:20:42
【问题描述】:
该代码是一个四字符密码生成器。我有一个 if/else break 系统设置,但我不知道为什么它不起作用。循环生成超出限制,直到用尽所有选项,我很难正确调试。除了javascript和HTML之外,我对任何东西都很陌生,所以任何帮助都会很有用。谢谢!
#include <iostream>
using namespace std;
int
main () {
char char1;
char char2;
char char3;
char char4;
int numPasswordsGenerated = 0;
cout << "Password Generator:" << endl;
/* Generates four-character passwords (excludin digits) by exhausting all character
options between '!' and '~' starting with the fourth character. Once the fourth
character exhausts all options, the third character increases by the next character
in the binary lineup, then continuing with the fourth character. This process continues
until the numPasswordsGenerated integer reaches the desired number, or the password
output becomes "~~~~"; whichever comes first.
*/
char1 = '!';
while (char1 <= '~') {
char2 = '!';
while (char2 <= '~') {
char3 = '!';
while (char3 <= '~') {
char4 = '!';
while (char4 <= '~') {
// cout << char1 << char2 << char3 << char4 << endl;
numPasswordsGenerated++; //!*FIXME*!
cout << numPasswordsGenerated << endl; //DEBUG DELETE
if (numPasswordsGenerated == 10)
break;
char4++;
}
char3++;
}
char2++;
}
char1++;
}
return 0;
}
【问题讨论】:
-
break语句只跳出最里面的循环,而不是全部四个。第三次向下循环然后进行下一次迭代,numPasswordsGenerated变为 11,不再满足条件。 -
在您在这里尝试做的事情的上下文中,JavaScript 与 C 或 C++ 没有任何不同。想想你将如何用你知道的语言调试和解决这个问题。
-
创建一个包含每个有效字符的数组,然后使用一个随机函数通过使用范围 for 循环来挑选出你想要多少个结果不是更容易吗?如果您希望我扩展我的意思作为答案,我可以,但它不能解决您的问题。它只是提供了一种替代解决方案。
-
感谢@IgorTandetnik!经过更多的测试后,我才注意到这一点。在我头上飞了一会儿!
-
@TheGrandJ 数组会更高效(而且肯定更容易),但我想看看是否可以将自己限制为仅循环语句。
标签: c++ loops if-statement while-loop