The following works for me ("number" is the key value and is set to 2):
Code:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <fstream>
using namespace std;
vector <char> read_file(string file_name);
string decode(vector <char> encrypted, int key);
void display(string decrypted, int key);
int main ()
{
int number = 2; //Key
vector <char> encrypted = read_file("intercepted.txt");
string decrypted = decode(encrypted, number);
display(decrypted, number);
cin.get();
return 0;
}
//--------------------------------------------
vector <char> read_file(string file_name)
{
ifstream input_file;
input_file.open(file_name.c_str());
if (input_file.fail())
{
cout << "Failed to open file!" << endl;
exit(1);
}
vector <char> encrypted;
char next(0);
while(input_file >> next)
{
encrypted.push_back(next);
cout << next;
}
cout << endl;
input_file.close();
return encrypted;
}
//-------------------------------------------
string decode(vector <char> encrypted, int key)
{
//Creates new vector
string decrypted = "";
for (int i = 0; i < encrypted.size(); i++)
{
if (int(encrypted[i]) + key > 126)
{
decrypted += char(((int(encrypted[i]) + key) - 127) + 32);
}
else
{
decrypted += char(int(encrypted[i]) + key);
}
}
return decrypted;
}
//------------------------------------------
void display(string decrypted, int key)
{
cout << "Key: " << key << " Text: " << decrypted << endl;
}
So, I still don't understand the need for the key loop, unless your objective is to find the key that works. But, then you would have to test the validity of the returned string each time...
But, if you wanted to, you would do it kind of like you had it before:
Code:
string decode(vector <char> encrypted, int key)
{
//Creates new vector
string decrypted = "";
for(key = 0; key < 100; key++)
{
for (int i = 0; i < encrypted.size(); i++)
{
if (int(encrypted[i]) + key > 126)
{
decrypted += char(((int(encrypted[i]) + key) - 127) + 32);
}
else
{
decrypted += char(int(encrypted[i]) + key);
}
}
//break from loop when valid string is found
}
return decrypted;
}