#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
char x[20];
cout << "enter something\n";
cin.getline(x,20);
ofstream o("d:/tester.txt");
//o.write( (char*)&x , sizeof(x) );
for(int i = 0 ; i<=19 ; i++ ) {
o.put(x[i]);
}
}
I am not getting that output in the file the one which i enter during program . for eg. the output is 畳慨汩朠灵慴찀쳌쳌쳌 on writing suhail gupta.
What is the problem with the code ? Even when i use o.write( (char*)&x , sizeof(x) ); (the commented statement) i get the same output.
What is the reason?
Your program involves undefined behavior. The
xarray is not fully initialized and you read from the uninitialized indices. Besides, you always write 20 bytes, independent of what you read from the user.I guess you use some text editor like Notepad. The latter has bugs when trying to guess the encoding. It appears that it guesses the file is UTF16 and displays
20/2 == 10characters instead.To solve the problem, store to the file exactly the number of characters entered by the user. Use
std::stringto make it easier.Edit: The C++ way: