Reputation: 13
I'm having issues I've never seen before since I've started messing with the XOR operator and simple, single character key encryption. The text always has a random ascii character at the end of it after it runs through the program a second time. Another issues is that the texts "Pre-order" and "Post-order" are modified alternatively after every iteration of the program. I'm sure most of this is simply due to beginner mistakes, especially a lack of experience with IO in the way that these issues are appearing.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream ifile;
ofstream ofile;
string toProc;
string file;
char key = ' ';
cout << "Enter file location: \n";
cin >> file;
cout << "Enter key: \n";
cin >> key;
ifile.open(file);
if(ifile.is_open())
{
char temp;
temp = ifile.get();
toProc.push_back(temp);
while(ifile.good())
{
temp = ifile.get();
toProc.push_back(temp);
}
ifile.close();
}
else
{
cout << "No file found.\n";
}
cout << "Pre action: " << toProc << endl;
for(int i = 0; i < toProc.size(); i++)
toProc[i] ^= key;
cout << "Post action: " << toProc << endl;
ofile.open(file);
ofile << toProc;
ofile.close();
}
Upvotes: 1
Views: 201
Reputation: 69957
The get()
function of std::ifstream
, which you use to retrieve characters from the input file, returns eof
(end-of-file) when it hits the end of the file. You need to check for this (instead of checking ifile.good()
in the loop).
The way it's written now, it takes the eof
as a character and appends it to the string. That (i.e. the xor'ed version of it) is the funny character you are getting in your output.
Here is a simple loop that reads characters from std::cin
using get()
and echos them on STDOUT
. It performs the check for eof
correctly. You can fit this into your code, using ifile
instead of std::cin
:
#include <iostream>
int main()
{
char c;
while ((c = std::cin.get()) != std::istream::traits_type::eof())
std::cout.put(c);
std::cout << std::endl;
return 0;
}
I should also mention that the get()
function reads character by character, and there isn't really any good reason for that. I would use getline()
or read()
to read bigger chunks.
Upvotes: 2