Cryptography does not read spaces

Asked

Viewed 95 times

2

Well, I’m trying to encrypt a text file with the following "program":

#include <iostream>
#include <fstream>
using namespace std;

void writeFile(char* filename, string str){
    ofstream f(filename);
    f << str;
}

string readFile(char* filename){
    string str;
    ifstream f(filename);
    f >> str;
    return str;
}
string encryptDecrypt(string toEncrypt) {
    char key[3] = {'K', 'C', 'Q'}; //Any chars will work
    string output = toEncrypt;

    for (int i = 0; i < toEncrypt.size(); i++)
        output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))];

    return output;
}

int main(int argc, const char * argv[])
{
    string encrypted = encryptDecrypt(readFile("file.lua"));
    cout << "Encrypted:" << encrypted << "\n";

    string decrypted = encryptDecrypt(encrypted);
    cout << "Decrypted:" << decrypted << "\n";

    return 0;
}

The content of the "file.lua" file is:

local a = ola

But the output of the program is:

Encrypted:',2*/ Decrypted:local

But if instead of :

string encrypted = encryptDecrypt(readFile("file.lua"));

me use:

string encrypted = encryptDecrypt("local a = ola");

It works normal, and the output gets:

Encrypted:',2*/qclk,= Decrypted:local a = ola

  • Hello Gabriel. As you may notice from the response you received, your problem is essentially the same of your other question. If you did not understand what is happening, you could have asked for more details there in the original question instead of opening another.

1 answer

3


The problem is that the operator >> eliminates all blank spaces (line breaks, spaces, tabs). That is, in the case you are only taking the first word, up to the space. The ideal would be to replace in the method readFile the line:

f >> str;

by this sequence of commands:

stringstream buffer;
buffer << f.rdbuf();
str = buffer.str();

This will read the entire file, including all whitespace.

  • Perfect. And also don’t forget to give #include <sstream>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.