#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) );
}
我得到了意外的输出。我没有得到我在字符串函数中写的内容。 为什么是这样 ? 请解释。
就像我编写 steve pro
时,我在文件中得到的输出为 8/steve pro ÌÌÌÌÌÌ ÌÌÌÌ
我希望输出是 steve pro
最佳答案
你把 std::string
当作它不是的东西。它是一个复杂的对象,在其内部某处为您存储字符。
没有理由假设一个字符数组位于对象的开头(&x
),而对象的sizeof
与多少个字符无关它可能间接持有/代表。
您可能正在寻找:
o.write(x.c_str(), x.length());
或者直接使用内置的格式化 I/O 机制:
o << x;
关于c++ - 这个程序有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6533041/