这个程序有什么问题?

pro*_*eve 1 c++ io visual-c++

#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) );
}
Run Code Online (Sandbox Code Playgroud)

我得到了意想不到的输出.我没有得到我在字符串函数中写的东西.为什么是这样 ?请解释 .

就像我写的时候steve pro我得到8/ steve pro ÌÌÌÌÌÌ ÌÌÌÌ文件中的输出

我希望输出是史蒂夫亲

Lig*_*ica 9

你正在对待std::string一些不是这样的东西.这是一个复杂的对象,在其内部的某个地方,为您存储字符.

没有理由假设字符数组位于object(&x)的开头,并且sizeof该对象与它可以间接保持/表示的字符数无关.

你可能正在寻找:

o.write(x.c_str(), x.length());
Run Code Online (Sandbox Code Playgroud)

或者只使用内置的格式化I/O机制:

o << x;
Run Code Online (Sandbox Code Playgroud)