16

如何将 5 个随机 ascii 值转换为字符?


迅速的:

随机生成从 97 到 122 的 5 个 ascii 值(所有字母表的 ascii 值)。边走边确定每个ascii值对应的字母,输出5个字母组成的单词。

我的代码:

#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main ()
{
srand (time(NULL));
int val1= rand()%122+97;
int val2= rand()%122+97;
int val3= rand()%122+97;
int val4= rand()%122+97;
int val5= rand()%122+97

cout<<val1<<" and "<<val2<<" and "<<val3<<" and "<<val4<<" and "<<val15<<". "<<






return 0;
}
4

2 回答 2

18
for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}
于 2013-10-21T02:17:35.153 回答
17

要将intASCII 值转换为字符,您还可以使用:

int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z
于 2017-07-16T02:49:16.073 回答