Encryption and Decryption Program in C++ using a class
Hi everyone,
I have gotten most of a encryption and decryption part of a C++ program to work but I am having problems with wrapping around the alphabet and I am getting weird characters for the encryption and decryption whenever I enter spaces in a line of text.
I have a program where the key code is 4. For example, if the user enters a line of text called "Hello World", it would then be ENCRYPTED as "Lipps Asvph" where letter in the alphabet increases by 4 letters where H becomes L, e becomes i and so on.
Here are the two problems I am having with this program:
The letter W (in the "Hello World" example) should wrap around to the beginning of the alphabet and become letter A but instead I am getting a weird character and not the letter A in my output. I am also getting weird characters in output anytime the user enters spaces in between words in the text line. These are the two problems that I want to correct.
Here is my code so far:
Code:
#include <iostream>
#include <string>
#include <conio.h>
class Encrypt {
private:
char line[80];
int key;
public:
void getdata();
void enc();
void dec();
void mix();
};
void Encrypt::getdata() {
cout <<"Enter a line of text: ";
cin.getline(line, 80);
}
void Encrypt::enc() {
int code;
int length;
char *enc;
key = 4;
enc = line;
length = strlen(line);
for (int i = 0; i < length; i++) {
*enc += key;
enc++;
}
cout << "Encrypted text is: " << line << endl;
}
void Encrypt::dec() {
int length;
char *dec;
key = 4;
dec = line;
length = strlen(line);
for (int i = 0; i < length; i++) {
*dec -= key;
dec++;
}
cout << "Decrypted text is: " << line << endl;
getche();
}
int main() {
Encrypt text;
text.getdata();
text.enc();
text.dec();
}
The first problem is that I can't get it to wrap around from the end to the beginning of the alphabet for encryption (Letter W to Letter A when key = 4) and vice versa (Letter A to Letter W) for decryption.
If anyone has any suggestions or advice for me on how to correct these two problems, it would be greatly appreciated.
Thanks.