Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ASCII value into char in C++?

Tags:

c++

ascii

How do I convert 5 random ascii values into chars?


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.

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;
}
like image 246
user2877477 Avatar asked Oct 21 '13 02:10

user2877477


People also ask

Can we assign integer value to char in C?

Because, char are data types which hold 1 byte (8 bits) of data. So in char you can store integer values that can be represented by eight bits. That is 0-255 in normal case.


1 Answers

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}
like image 106
Riftus Avatar answered Oct 06 '22 00:10

Riftus