For my program I am supposed to implement an encryption and decryption algorithm.
You will read the input from a file, “plaintext.txt” The file will contain plaintext strings that are all lowercase, and be of the format:
3 hello world
2 how are you
Each line contains an integer as the first thing in the line, representing the key, k, that is used in the encryption (and decryption) shift.
There will be no numbers or punctuation in the plaintext input string.
So far I created a function, parseString( ), that takes the inputString, and stores the key and the plaintext in the other two parameters. The problem is trying to implement the encryption and decryption functions. Can anyone please help me try to fix my functions for encryption and decryption? Thanks
This is my code so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//parseString
//INPUT:
// inputString : the entire line you read from file
//OUTPUT:
// plainText : a string reference, which will include everything except the integer in the front
// key : an int reference. This will be the key taken from the beginning of the line
void parseString(string inputString, string& plainText, int& key);
void encryption(string plainText, int key);
void decryption(string plainText, int key);
int main()
{
ifstream infile;
string tempString;
string plaintext;
int key = 0;
infile.open("plaintext.txt");
while(!infile.eof())
{
getline(infile, tempString, '\n'); //read line until newline is encountered
parseString(tempString, plaintext, key);
cout<<"Plaintext : "<<plaintext<<endl;
cout<<"Key : "<<key<<endl;
}//end while
encryption(plaintext, key);
decryption(plaintext, key);
infile.close();
return 0;
}
void parseString(string inputString, string& plainText, int& key)
{
int spaceIndex = 0;
string tempKey; //will hold the string version of the key before conversion
spaceIndex = inputString.find_first_of(" "); //finds the first whitespace
tempKey = inputString.substr(0,spaceIndex); //capture the data up to the first white space
key = atoi(tempKey.c_str()); //convert the char* equivalent of tempKey to integer (atoi = ASCII to int)
plainText = inputString.substr(spaceIndex+1, inputString.length()-spaceIndex);
}
void encryption(string plainText, int key)
{
string temp;
for(int i=0; i <plainText.length();i++)
{
temp= plainText[i] + key;
}
cout << "Encrypted text is " << temp << endl;
}
void decryption(string plainText, int key)
{
string temp2;
for (int i = 0; i < plainText.length(); ++i)
{
temp2= plainText[i] - key;
}
cout << "Decrypted text is " << temp2 << endl;
}