Finn Stubbings Finn Stubbings - 1 month ago 12
C++ Question

Code ignoring if statements - C++

I've been working on a password generator for my College coursework, and one of the parts to this involves creating 'Complex' passwords, which are passwords which are nothing more than strings of random characters, and the user should be able to specify what types of characters are used. However, the set of if statements which control if a function is used don't activate based on the values within uppertrue numbertrue and lowertrue, they all act as if the statement returns true, and so the function is always run.
#include
#include
#include
#include

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;
}


if anyone can point me in the correct direction it would be much appreciated, it seems like it's a logical error but I can't see anything logically wrong with it. Is it perhaps to do with some sort of quirk with C++? (bearing in mind I was taught C and this is the first thing I've done in C++)
Many thanks
(A comment said to remove the part where i'd usually enter the values for uppertrue etc so i've hardcoded the values to show the problem instead)

Answer

Your problem is here:

int lower()     //same as upper but for lower case
{
    return rand() % 122 + 26;
}

It will produce random number in range 26 ... 147. Which is something completely different than range for lower case characters. You want this:

    return rand() % ('z' - 'a' + 1) + 'a';

You should fix the other functions in similar manner.

Note to those who worry about their code being able to run on, for example, mainframes using EBCDIC character encoding: This assumes that a..z have continuous character codes.