I made a program that can choose random numbers, and write them to a text file. I was wondering how you could assign each number to a letter to be written in the text file. I know you can do:
if (value == 1)
myfile << "a";
because I tried.
I want to know if there was an easy way, using arrays to do it. Here is the code in case you want it:
If you generate a random number between [ 0...25 ] inclusive, then simply adding 'A' to it will convert the
random number to a letter between A and Z. Adding 'a' to it will convert the number to a lower case letter.
Try this:
1 2 3
int num = rand() % 26; // Number in the range [ 0...25 ]
char upper = static_cast<char>( 'A' + num ); // Convert to upper case
std::cout << upper << std::endl;
If you need help, google around "Caesar cipher". That is a basic shift cipher, which is a variation of a substitution cipher, which is what you are trying to do.
(The basic difference appears that you are writing the indices directly into the file instead of converting them to another letter.)
Simply, order your alphabet randomly (in your array), and you have a lookup key: the letter and its index into the array. Deciphering requires just converting the index back into the letter.
To clarify, here is the English alphabet:
A B C D E F ... W X Y Z
0 1 2 3 4 5 ... 22 23 24 25
Here is the Caesar cipher alphabet:
C D E F G H ... Y Z A B
0 1 2 3 4 5 ... 22 23 24 25
You can arrange your alphabet in any order:
N Q Z X F T ... A R V E
0 1 2 3 4 5 ... 22 23 24 25
I get what you're saying Duoas, and I tried it. The only problem is that is says that all of the letters are undeclared identifiers. Here's my revised code:
In your previous post you're initializing int-type variable letters, then you're assigning variable a's value to variable 1 and so on... Only variable letters was initialized (without any assigned value), the rest of them weren't. I think you meant to write:
char letters[] = {'a', 'b', 'c', 'd', 'e'};
I'm sure there exists much more efficient way to do this, but I think this is good enough:
Write a program that automatically generates the first 20 lowercase letters of the English alphabet; DO NOT declare and set 15 different variables or constants.
The letters must be displayed in a number of columns initially set by the user. The numbers have to be aligned in columns (see output below). The maximum number of columns is 5, while the minimum is 1.
can yall help me !