我一直在为我的大学课程设计一个密码生成器,其中一个部分涉及到创建'复杂'密码,这些密码只不过是随机字符串的密码,用户应该能够指定使用什么类型的字符。但是,控制函数是否使用的if语句集不会基于uppertrue numbertrue和lowertrue中的值进行激活,它们的作用就像语句返回true一样,因此函数始终运行。 的#include 的#include 的#include 的#include代码忽略if语句 - C++
int upper(), lower(), number(), symbol(); //initializing functions to be used to generate the ascii code
int clength = 15;
int pass[30];
int uppertrue = 0, numbertrue = 1, symboltrue = 0;
int main()
{
srand (time(NULL)); //seed random generator
int i = 0; //counter
int which = 0;
do
{
which = rand() % 4 + 1; //randomly decides which type of character will be shown - probablity is unweighted for complex module
if (which == 1)
{
pass[i] = lower(); //inserts the code returned by the function into the array
i++;
}
else if ((uppertrue == 1) && (which == 2))
{
pass[i] = upper();
i++;
}
else if (numbertrue == 1 && which == 3)
{
pass[i] = number();
i++;
}
else if (symboltrue == 1 && which == 4)
{
pass[i] = symbol();
i++;
}
}while (i!=(clength+1)); //terminates loop when the array is complete
std::string strpass;
int x=0;
do
{
char tempchar;
tempchar = pass[x];
std::cout << tempchar;
x++;
}while (x!=15);
return 0;
}
int upper() //creates random number between the range of ascii characters that results in caps
{
return rand() % 65 + 26;
}
int number() //same as upper but for numbers
{
return rand() % 48 + 9;
}
int lower() //same as upper but for lower case
{
return rand() % 122 + 26;
}
int symbol() //same as upper but for symbols (currently only supporting a few characters
{
return rand() % 63 + 6;
}
如果有人能在正确的方向,将不胜感激指向我,好像它是一个逻辑上的错误,但我看不出什么错逻辑用它。这可能与C++的某种怪癖有关吗? (记住我被教过C,这是我在C++中做的第一件事) 非常感谢 (评论说删除部分,我通常会输入uppertrue等的值,所以我硬编码值显示,而不是问题)
请稍微减少问题。对于初学者来说,摆脱'std :: cin'调用并将其替换为硬编码输入以尽可能简洁地展示问题。见http://stackoverflow.com/help/mcve –
这不是你问的问题,但你需要做'rand()%26 + 65'和'rand()%26 + 97'(不是122)。你可以用'rand()%('Z' - 'A'+ 1)+'A''和'rand()%('z' - 'a'+ 1)+'a' '' –
除了(不正确的)幻数之外,'lower()','upper()','number()'和'symbol()'的代码是不可移植的。 'number()'很容易实现:return rand()%10 +'0';'。其他的应该用一个'char'实现:'char lc [] =“abcdefghijklmnopqrstuvwxyz”;'然后'return lc [rand()%26];'。 –