Re: encryption problem
I'm a newbie too so it took me a few minutes to realize what went
wrong with your code. I'm sure i'll get flamed (especially when the
blind is leading the blind) but i'm hoping someone will correct both
of us so we can do better next time.
Here is your code:
#include <iostream>
#include <string>
using namespace std;
char alphabet[27] = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
char plain_text[27];
int string_length;
int main()
{
cout << "text: ";
cin >> plain_text; // plain_text = "test"
string_length = strlen(plain_text); //string_length is 4;
for(int i=0; i < string_length; i++) // do this 4 times
{
plaintext[i] = alphabet[i]; // take alphabet[i] which is Z, then Y,
then X then W and assign it to plaintext[0-4] which equates too ZYXW;
}
cout << plain_text; // output ZYXW
system ("PAUSE");
-----------------------------
Here are my thoughts:
#include <iostream>
#include <string.h>
using namespace std;
// this should be a list of all possible characters that can be
converted
char decrypted[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// list of the corresponding converted text
char encrypted[27] = "ZYXWVUTSRQPONMLKJIHGFEDCBA"; //encrypted key
char plain_text[80]; //plain text string
char converted_text[80]; //converted string for output
int string_length; // initialize the string
int main()
{
cout << "text: "; // enter some text
cin >> plain_text; //assign the array of text to plain_text
string_length = strlen(plain_text); //find the length of the text
string entered by the user
for (int i=0; i<string_length; ++i) // for the current character in
the string (i is the current character)
{
for (int j=0; j<(strlen(decrypted)); j++) //for the number of
possible decrypted characters
{
if (decrypted[j] == plain_text[i]) //if the current character
matches in the possible list of decrypted characters
{
converted_text[i] = encrypted[j]; //then take the corresponding
encrypted character and assign it to the converted text string
}
}
}
cout << converted_text << "\n";
return 0;
}
------------------------
Here are my thoughts:
- i used a "decrypted" but incomplete list of possible characters
entered. Its probably a better idea to compare every character with
the entire list of ascii characters and output an offset (rather than
depending on a 1-to-1 translation on manually entered character list)
That shouldn't be too difficult.
- i'm not sure i'm adhering to any proper coding practices by using a
variable from one for-loop as a basis for comparison in a nested for
loop. Should these "constructs" (is that an appropriate word?) allow
mingling of variables?
- should I move the for-loops and character comparisons to a function
outside of main()?
Any other critiques would be appreciated. Please keep in mind i'm a
newbie so additional explanation and examples would be helpful.
Thanks!