背景:我正在用c++做一个密码生成器,基本上它使用rand生成数字,这些数字直接对应ASCII字符。
因此,生成数字很容易,但我需要将其转换为 ASCII 等价物,才能真正生成可用的密码。
#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;
}
}
}
在我上面发布的代码中,您可以看到我上次尝试公然告诉程序变量“character”需要用作实际字符。
好吧,似乎有点困惑。 Rand 生成一个介于 65 和 90 之间的数字。这些数字对应于 ASCII 表中的大写字母。我想将字母打印到控制台,而不是生成的数字。
最佳答案
当你写这个的时候
char print = character;
您告诉编译器您希望它初始化变量 print
为变量 character
的当前值(恰好在时间)。如果要将当前值设置为不同类型的变量,需要在character
重新赋值后进行:
character = rand()%(90-65+1)+65;//Determines Uppercase character to be generated.
print = (char)character;
cout<<print<<endl;
不过,您不必重新分配,因为直接在打印前进行转换就足够了:
character = rand()%(90-65+1)+65;//Determines Uppercase character to be generated.
cout<<(char)character<<endl;
注意:虽然使用 ASCII 字符的十进制值没问题,但如果您改用字符常量,代码将更易于阅读:
character = rand()%('Z'-'A'+1)+'A';
关于c++ - 如何将整数转换为其等效的 ascii,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34959134/