-
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;
}
-
ok, so now since all of the values are read out from key = 0 to key = 100. is there a way to individually ask the user if each decrypted string at key = x is the one they want. So, what I'm asking is if there is a way to output decrypted after each reiteration of key and ask the user if it is correct. if yes, it exits the function and if no, it continues that loop while asking the user after each iteration of key. please help asap! i appreciate the help! thanks
-
Just ask the user after the string is filled, right before the next key iteration (where my comment is). If it is the correct string, break from the for loop. Then the return statement executes, which will be the correct string.
-
got it. the program works the way i want it to. thanks for all the help everyone!! most appreciated!