I wrote a program which was supposed to decrypt a file encrypted with the XECryption algorithm. Now, I know the decryption algorithm, but I have a problem with my ifstream object. It doesn't read anything at all, and the ofstream object just outputs a single random byte in a never ending loop. I've tried using cin, which works correctly, but it's not what I want.
#include <fstream>
#include <iostream>
usingnamespace std;
int main()
{
ifstream in("file.in", ios::in);
if (!in.is_open())
{
cout << "File didn't open!\n";
in.close(); /* I'm a little unsure about this. If the file didn't open,
do I really have to close it? */
cin.get();
return 0;
}
if (in.fail())
{
cout << "File failed before reading!\n";
in.close();
cin.get();
return 0;
}
ofstream out("file.out");
int one;
int two;
int three;
int byte;
while (!in.eof())
{
in >> one >> two >> three;
byte = one + two + three;
out << (char) byte;
}
cout << "Closing file!\n";
in.close();
out.close();
cin.get();
return 0;
}
I'm doing this on a Windows 8(.1) pc with Code::Blocks 13.12. In the file (file.in) I have replaced the points with spaces. What is wrong with the code?
How embarassing, hypercorrection! I still have problems though; when I remove the exclamation mark, the object in does not fail, but my out object just writes a single byte in file.out in a never ending loop. In this case 'ยข'.
I still think it's the in object that's the problem. If I use cin instead, I don't have the same problem.
while(in >> one >> two >> three)
{
byte = one + two + three;
out << (char) byte;
}
And for the other question, no you don't have to explicitly call the close function. The destructor of the ifstream takes care of that after it goes out of scope.
That's because the out stream is opened and closed but otherwise not used.
Yes, sorry about that. I have tried with both out and cout, but there is no output either in file.out or on the screen. That indicates an error with in, I think.
that is, a set of three integers separated by dots. When reading from the file, you need to account for those separators:
Yes, as you realised later, I had replaced the dots with spaces, but I did try your alternative now, just to be sure (after replacing the spaces with dots again, of course). Still nothing.
But the code I posted worked - using Turbo C++ 3.0 and the very limited data file which I posted (contained only two characters after decrypting).
Success! I realised there was nothing wrong with the program itself, but the text file wasn't ANSI encoded. I'm sorry for this meaningless thread, but at least you taught me not to use the eof() method.