C++ 将 ascii 值转换为 char

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19485227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:54:21  来源:igfitidea点击:

Convert ascii value to char

c++ascii

提问by user2877477

How do I convert 5 random ascii values into chars?

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



Prompt:

迅速的:

Randomly generate 5 ascii values from 97 to 122 (the ascii values for all of the alphabet). As you go, determine the letter that corresponds to each ascii value and output the word formed by the 5 letters.

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

My Code:

我的代码:

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

回答by Riftus

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

回答by A-Sharabiani

To convert an intASCII value to character you can also use:

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

int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z