#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string x;
getline(cin,x);
ofstream o("f:/demo.txt");
o.write( (char*)&x , sizeof(x) );
}
I get the unexpected output.I don’t get what i write in a string function.
Why is this ?
Please explain .
Like when i write steve pro i get the output as 8/ steve pro ÌÌÌÌÌÌ ÌÌÌÌ in the file
I expect that the output be steve pro
You are treating an
std::stringlike something that it is not. It’s a complex object that, somewhere in its internals, stores characters for you.There is no reason to assume that a character array is at the start of the object (
&x), and thesizeofthe object has no relation to how many characters it may indirectly hold/represent.You’re probably looking for:
Or just use the built-in formatted I/O mechanism: