Context: I am making myself a password generator in c++, basically it uses rand to generate numbers, and these numbers correspond directly to ASCII characters.
So, generating the numbers is easy, but i need to convert this to their ASCII equivalents to actually make a usable password.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main ()
{
//Initializing variables.
int type = 0;
int character = 0;
char print = character;
//Generator.
srand(time(NULL));
for (int i=0; i<10;i++)
{
type = rand()%(3-1+1)+1;//Determines: 1 = Uppercase, 2 = Lowercase, 3 = Number.
if (type == 1)//If Uppercase.
{
character = rand()%(90-65+1)+65;//Determines Uppercase character to be generated.
cout<<print<<endl;
}
if (type == 2)//If Lowercase.
{
character = rand()%(122-97+1)+97;//Determine Lowercase character to be generated.
cout<<print<<endl;
}
if (type == 3)//If Numerical.
{
character = rand()%(57-48+1)+48;//Determines Number to be generated.
cout<<print<<endl;
}
}
}
In the code i posted above, you can see i last tried blatantly telling the program that the variable "character" needs to be used as an actually character.
Ok so there seems to be a bit of confusion. Rand generates a number say between 65 and 90. These numbers correspond to capital letters on the ASCII table. I want to print to the console the letter, not the generated number.
When you write this
char print = character;
you tell the compiler that you want it to initialize variable print
to the current value of variable character
(which happens to be zero at the time). If you want the current value to be set to a variable of different type, you need to do it after a reassignment of character
:
character = rand()%(90-65+1)+65;//Determines Uppercase character to be generated.
print = (char)character;
cout<<print<<endl;
You do not have to do reassignment, though, because a cast directly before printing will be sufficient:
character = rand()%(90-65+1)+65;//Determines Uppercase character to be generated.
cout<<(char)character<<endl;
Note: although it is fine to use decimal values of ASCII characters, the code becomes easier to read if you use character constants instead:
character = rand()%('Z'-'A'+1)+'A';