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;
}
<random>
header.rand
is rather sucky when there are better PRNGs likestd::mt19937
right around the corner, andstd::uniform_int_distribution
actually gives a uniform distribution, unlike the modulus bias here. Plus it's plain to see what the range is. channel9.msdn.com/Events/GoingNative/2013/…rand()%122
produces a value in the range [0, 122). Adding 97 to such a value produces a value in the range [97, 219). Not what you wanted.