gpt4 book ai didi

c++ - 跳出内部循环并不会终止循环

转载 作者:行者123 更新时间:2023-12-03 06:54:56 25 4
gpt4 key购买 nike

该代码是一个四字符密码生成器。我有一个 if/else 中断系统设置,但我不明白为什么它不起作用。循环生成超过限制,直到用尽所有选项,我很难正确调试。我对 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 使用 return

请记住,break 只会跳出您所在的循环,而不是函数范围内的所有循环。

这是一个修改后的版本,使用 argv 对限制进行了更灵活的输入安排:

#include <iostream>

void generatePasswords(const size_t limit) {
char password[5];
size_t count = 0;

password[4] = 0;

password[0] = '!';

while (password[0] <= '~') {
password[1] = '!';

while (password[1] <= '~') {
password[2] = '!';

while (password[2] <= '~') {
password[3] = '!';

while (password[3] <= '~') {
password[3]++;

std::cout << password << std::endl;

if (++count >= limit) {
return;
}
}

password[2]++;
}

password[1]++;
}

password[0]++;
}
}

int main(int argc, char** argv) {
std::cout << "Password Generator:" << std::endl;

generatePasswords(argc >= 2 ? atoi(argv[1]) : 1000);

return 0;
}

注意使用 char password[5] 而不是一堆不相关的字符。

关于c++ - 跳出内部循环并不会终止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64201340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com