试图在C中制作一个随机的“密码生成器”

#include  #include  #include  int main() int counter = 0; srandom(time(NULL)); // Correct seeding function for random() char randChar; int passwordLength; printf("Give password length \n"); scanf("%d", &passwordLength); while (counter < passwordLength) { randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random() % 62]; printf("Your password is: %c", randChar); counter++; } if (passwordLength 25) { printf("Your password must be from 5 to 25!!"); } printf("\n"); return 0; } 

长话短说我试图让这个程序工作但由于某些原因我不知道如何让它工作。谢谢提前。

首先,回顾一下您尝试使用的逻辑。

 if (passwordLength < 5 && passwordLength>25) { printf("Your password must be from 5 to 25!!"); } 

没有价值,可以同时小于5 大于25。 您需要检查其中任何一个,而不是两个。 使用逻辑OR运算符|| 代替。

也就是说,扫描值后立即检查条件可能是有意义的。 计算很多东西是没有意义的,然后根据很久以前就已经知道的情况把它扔掉。

此外,始终检查scanf()的返回值以确保成功扫描,否则您最终可能会使用不确定的值。

除了Sourav的答案中发现的逻辑问题,还有一个编译错误。

但是,通过查看编译器输出,问题并不明显:

 /tmp/x1.c: In function 'main': /tmp/x1.c:7: error: parameter 'counter' is initialized /tmp/x1.c:8: error: expected declaration specifiers before 'srandom' /tmp/x1.c:13: error: expected declaration specifiers before 'printf' /tmp/x1.c:14: error: expected declaration specifiers before 'scanf' /tmp/x1.c:16: error: expected declaration specifiers before 'while' /tmp/x1.c:22: error: expected declaration specifiers before 'if' /tmp/x1.c:26: error: expected declaration specifiers before 'printf' /tmp/x1.c:27: error: expected declaration specifiers before 'return' /tmp/x1.c:28: error: expected declaration specifiers before '}' token /tmp/x1.c:11: error: declaration for parameter 'passwordLength' but no such parameter /tmp/x1.c:9: error: declaration for parameter 'randChar' but no such parameter /tmp/x1.c:7: error: declaration for parameter 'counter' but no such parameter /tmp/x1.c:28: error: expected '{' at end of input 

通常情况下,您首先查看顶部的错误并修复它,然后查看是否可以进一步消除其他错误。 在这种情况下,真正的线索实际上是在最后。

你错过了mainfunction的左大括号。 添加它,它将成功编译并打印一个随机密码(没有正确检查长度)。

它不是if(passwordLength < 5 && passwordLength >25)而是||

必须scanf之后立即检查passwordLength变量。 如果失败,程序必须返回

不需要counter ,而是for循环

如果您需要存储密码以便稍后处理,我建议您将其存储在变量中

 int main(){ srandom(time(NULL)); char randChar; int passwordLength; printf("Give password length: "); scanf("%d", &passwordLength); if(passwordLength < 5 || passwordLength >25){ printf("Your password must be from 5 to 25!!"); return 1; } char pwd[passwordLength]; for(int i = 0; i < passwordLength; i++){ randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random() % 62]; pwd[i] = randChar; } printf("%s\n", pwd); return 0; }