我一直在爲我的大學課程設計一個密碼生成器,其中一個部分涉及到創建'複雜'密碼,這些密碼只不過是隨機字符串的密碼,用戶應該能夠指定使用什麼類型的字符。但是,控制函數是否使用的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];'。 –