我正在写一个找到密码的程序.当我看到替换部分密码的"for"循环必须为所选密码长度的变量重复时,我遇到了一个问题.该程序的目标是生成并检查任何字符数组的密码,从"0"开始并经过"?(n次)",其中"0"是第一个字符和"?" 是最后一个角色.
有没有什么方法可以重复一次for循环多次而不需要单独编码?
请注意,基于广受好评的评论:
"重复一个for循环"可能更正确地表达为"嵌套几个for循环".
int maxLength = 32; //Length of the password, changes via input
char output[maxLength] = "";
for (int currentLength = 1; currentLength < maxLength + 1; currentLength++) {
for (int characterNumber = 0; characterNumber < 96 /*characters found with switch/case, 95 total*/; characterNumber++) {
for (int position = currentLength /*position in string*/; position > 0; position--) {
//For loops of character and position currentLength times
char newCharacter = '\0'; //Avoiding not initialized error, could be and character
output[position - 1] = getChar(characterNumber, newCharacter);
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出的例子是:... 01,02,03 ...,10,11 ......,a0,a1 ......,???? 4afuh7yfzdn_)aj901 ......
您不需要重复for循环.相反,你需要嵌套它.
实现它的最有吸引力的解决方案是递归构造.
伪代码:
void nestloop(int depth, int width)
{
if(depth>0)
{
int i;
for (i=0; i<width; i++)
{
nestloop(depth-1, width);
}
} else
{
/* do whatever you need done inside the innermost loop */
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
308 次 |
| 最近记录: |