If you want to write non-text data, you should open the file in binary mode:
ofstream ofile("file.txt", ios_base::binary);
A good practice is to check if the file was actually opened successfully:
ofstream ofile("file.txt", ios_base::binary); if (!ofile) return -1;
Until you close the file, there's a high chance the buffer is not flushed, so there's no point in reading the file in another stream before you close it:
ofile << x; ofile.close();
A good idea is to finish the output to cout with endl:
cout << (int) y << endl;
So you need something like:
#include <iostream> #include <fstream> using namespace std; int main() { char x = 26; ofstream ofile("file.txt", ios_base::binary); if (!ofile) return -1; ofile << x; ofile.close(); ifstream ifile("file.txt", ios_base::binary); if (!ifile) return -1; char y; ifile >> y; cout << (int) y << endl; ifile.close(); return 0; }