如何在C ++中将ASCII值转换为字符?

22

我该如何将5个随机ASCII值转换为字符?


问题描述:

从ASCII值97至122(即字母表的所有ASCII值)中随机生成5个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;
}

cout << (char)val1 << etc.. 实际上,你一开始就不应该使用 int。 - Alden
2
当有更好的 PRNGs,如 std::mt19937 就在附近时,rand 是相当糟糕的。而 std::uniform_int_distribution 实际上提供了一种 均匀 的分布,不像这里的模数偏差。另外它很容易看出范围是什么。http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful - chris
4
rand()%122 会生成一个范围在 [0, 122) 内的值。将这个值加上 97 将会得到一个范围在 [97, 219) 内的值,这可能不是你想要的结果。 - Igor Tandetnik
5
如果你要在三个小时内提出6个问题,也许你应该花更多的时间学习一本正式的书籍 - Benjamin Lindley
1
扩展Chris的评论,查看实时演示:http://ideone.com/pEhIDI - WhozCraig
显示剩余4条评论
4个回答

24

要将一个 int 类型的 ASCII 值转换为字符,您还可以使用以下方法:

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

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

1
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {

    int random;
    time_t current_time = time(NULL);

    // Providing a seed value
    srand((unsigned) time(NULL));

    // For Loop
    for (int i = 0; i < 5; i++)
    {
        int random = 97 + (rand() % 26);
        cout << "Random Letter: " << char(random) << endl;
    }
    return 1;
}

current_time变量保存了自1970年1月以来经过的秒数。该值传递给srand()函数,然后我们得到一系列伪随机数。

种子值在程序中只提供一次,无论要生成多少个随机数。

for循环按照问题的要求迭代5次。random函数生成一个数字,介于97和123之间,表示ASCII表中26个字母在其适当位置上的字符。

然后我们有一个简单的输出,使用Char()函数输出。该函数接受一个整数值,并输出相应的ASCII相关字符。


0
int main() 
{

    int v1, v2, v3, v4, v5,v6,v7;
    cout << "Enter 7 vals ";
    cin >> v1 >> v2 >> v3 >> v4 >> v5 >> v6 >> v7;

    cout << "The phrase is " 
         << char(v1) 
         << char(v2) << " "
         << char(v3) << " "
         << char(v4) 
         << char(v5) 
         << char(v6)  
         << char(v7);

        system("pause>0");
}

这个答案提供了什么好处?例如,为什么要使用char()而不是std::to_chars或std::to_string,正如此答案所建议的那样? - Sonic78
我只是分享我做的方式。它也适合初学者(就像我一样),因此易于理解,不涉及所有高级函数或策略。如果你对这个主题非常了解,请在论坛上友善地交流。 - Aoi Hyoudou

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接