After fixing line 3 (you should be including <string>, not <cstring>), this works as expected. Though I think I expect something different from you.
The reason the output is the same as the input is because there is no "encryption" here. You're not encrypting anything, you're just writing characters to a file, then reading them back. So logically, whatever you read back is going to be the same as what you wrote.
I think your confusion comes from the conversion of characters to integers. Let me back up and explain what happens here...
For all of these examples, let's say the user inputs the string "1111".
With your above char array, each of those '1' characters will be treated as characters. The ASCII code for the '1' character is 0x31 (or 49 if you don't like hex). Try this out:
1 2 3 4
|
if('1' == 0x31) // or ('1' == 49)
{
cout << "this will print";
}
|
So if you have a 4-element char array, with each char containing the '1' character, when you write this to a binary file, it will write the binary value of whatever is contained in those characters. In this case... 0x31.
If you were to open the file in a hex editor, you would see this:
Now... same thing.. but instead of putting that input in a char array.. let's put it in an
int
:
1 2 3 4
|
int buffer;
fstream FILE( "File.dat" ,ios::in | ios::out | ios::binary | ios::trunc);
cin >> buffer;
|
Here... cin acts differently. Instead of taking the characters the user inputs and copying them directly over (like it does for chars), it will attempt to convert their input into an integral value. So "1111" the string becomes 1111 the integer value.
While the char array stores each individual digit as a character, an int doesn't do that. Instead the 4 bytes represent the value in 2's compliment fashion.
So if you were to write this int to a file... then open the file in a hex editor... you would see this:
This is because 0x00000457 == 1111