1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
/*
* Author: Ima Student
* Date: April 7th, 2009
* Description: Program to encode messages using an ASCII substitution cypher
*/
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
void get_input(string& message, int& key);//declarations
vector<char> encrypt(string message, int key);
void display(vector<char> encrypted);
void save_file(vector<char> encrypted);
int main ()
{
string message;
int key;
get_input(message, key);
vector<char> encrypted = encrypt(message, key);
display(encrypted);
save_file(encrypted);
return 0;//Is the driver for all of the functions
}
void get_input(string& message, int& key)
{
cout << "Please enter the message to be encrypted on a single line: " << endl;
getline(cin, message);
cout << "Please enter a key between 1 and 100 for use in encrypting your message: ";
cin >> key;//standard enough, read in the input of the message, including whitespace, and stores it in the string "message" also takes the key value
}
vector<char> encrypt(string message, int key)
{
vector<char> encrypted;
for (int i = 0; i < message.length(); i++){
if (int(message[i]) + key > 126){//keeps the encoding in the regular ASCII keyset, also prevents the use of the DEL char
encrypted.push_back(char(32 + ((int(message[i]) + key) - 127)));//adds a charecter to the vector "encrypted" and wraps the count back to 'space'
}else{
encrypted.push_back(char(int(message[i]) + key));//adds a charecter to the vector "encrypted"
}
}//uses the method push_back, which add a charecter at the end of the current vector, after the current last element
cout << endl;
return encrypted;
}
void display(vector<char> encrypted){
cout << "After encrypting your message reads:" << endl;
for (int i = 0; i < encrypted.size(); i++){
cout << encrypted[i];
}//uses a for loop to display all the elements of the vector, the loop is kept in bounds by the use of the built in function size()
cout << endl;
}
void save_file(vector<char> encrypted){
ofstream output_file;
output_file.open("encrypted.txt");
for (int i = 0; i < encrypted.size(); i++){
output_file << encrypted[i];
}//almost the same as above, excepet instead of outputting to the terminal, outputs a file, supposedly for "dillivery".
output_file << endl;
output_file.close();
}
|