Encryption does not read spaces [duplicate]

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 "file.lua" 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"));

I use:

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

It works normal, and the output is:

  

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

    
asked by anonymous 30.04.2015 / 12:14

1 answer

3

The problem is that the >> operator eliminates all whitespace (line breaks, spaces, tabs). That is, in case you are only getting the first word, even the space. The ideal would be to substitute 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 whole file, including all the blanks.

    
30.04.2015 / 13:06