This one is different from the previous code I posted because here, as it uses a key file as the key instead of a hard-coded one.
The code:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
char line[250]={'\0'}; //For input data
char line_c[250]={'\0'}; //For coded/decoded data
char line_key[250] = {}; //Key
//array storing the alphabet
char code[68]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'1','2','3','4','5','6','7','8','9','0','_','.',',','!','\'','?'};
/*
* Ciphers a character.
*/
char get_ciphered(char character){
char ch = '\0';
for (int i=0; i<68;i++){
if ((character==code[i])){
ch = line_key[i];
break;
}
}
return ch;
}
/*
* Deciphers a character
*/
char get_deciphered(char character){
char ch = '\0';
for (int i=0; i<68;i++){
if ((character==line_key[i])){
ch = code[i];
break;
}
}
return ch;
}
/*
* Ciphers a line of input
*/
void encode_simple(){
int temp=0;
char temp_1 = '\0';
for (int i = 0; i<250; i++){
if (line[i]=='\0') break;
temp=get_ciphered(line[i]);
if (temp!='\0'){
line_c[i]=temp;
}
else{
line_c[i]=line[i];
}
}
}
/*
* Deciphers a line of input
*/
void decode_simple(){
int temp=0;
char temp_1 = '\0';
for (int i = 0; i<250; i++){
if (line[i]=='\0') break;
temp=get_deciphered(line[i]);
if (temp!='\0'){
line_c[i]=temp;
}
else{
line_c[i]=line[i];
}
}
}
/*
*
*/
int main(int argc, char** argv) {
//for input and output files
ifstream input1;
fstream output1;
ofstream output2;
//for key
ifstream key;
input1.open("input1.txt",ios::in);
output1.open("output1.txt",ios::out);
//set key array from file
key.open("key.txt",ios::in);
key>>line_key;
for (int i = 0;i<68; i++){
if (line_key[i]==0){
cout<<"null character";
line_key[i] = '+';
}
}
//cipher input1 and put to output 1
while(!(input1.eof())){
memset(line,'\0',250);
memset(line_c,'\0',250);
input1>>line;
encode_simple();
output1<<line_c<<endl;;
}
input1.close();
output1.close();
output1.open("output1.txt",ios::in);
output2.open("output2.txt",ios::out);
//decipher output1 and put to output 2
while(!(output1.eof())){
memset(line,'\0',250);
memset(line_c,'\0',250);
output1>>line;
decode_simple();
output2<<line_c<<endl;
}
output1.close();
output2.close();
return 0;
}