这个程序有什么问题?

时间:2011-06-30 09:57:53

标签: c++ visual-c++ io

#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

4 个答案:

答案 0 :(得分:9)

你正在对std::string之类的东西进行处理。这是一个复杂的对象,在其内部的某个地方为你存储角色。

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

你可能正在寻找:

o.write(x.c_str(), x.length());

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

o << x;

答案 1 :(得分:4)

您似乎有sizeof的错误模型,所以让我试着把它弄好。

对于x类型的任何给定对象T,表达式sizeof(x)是编译时常量。 C ++永远不会在运行时实际检查对象x。编译器知道x属于T类型,因此您可以想象如果愿意,它会将sizeof(x)静默转换为sizeof(T)

#include <string>

int main()
{
    std::string a = "hello";
    std::string b = "Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.";
    std::cout << sizeof(a) << std::endl;   // this prints 4 on my system
    std::cout << sizeof(b) << std::endl;   // this also prints 4 on my system
}

相同类型的所有C ++对象占用了确切的内存量。当然,由于字符串的长度差别很大,因此它们将在内部存储指向堆分配的内存块的指针。但这与sizeof无关。它不可能,因为正如我所说,sizeof在编译时运行。

答案 2 :(得分:2)

你得到的就是你写的东西:指向char的指针的二进制原始值......

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    string x;
    getline(cin,x);
    ofstream o("tester.txt");
    o << x;
    o.close();
}

如果您坚持直接编写缓冲区,则可以使用

o.write(x.c_str(), x.size());

PS 对代码格式的一点关注unclouds the mind

答案 3 :(得分:0)

您正在传递对象的地址以写入文件,而原始内容位于其他位置,由其内部指针指向。

试试这个:

string x;
getline(cin,x);
ofstream o("D:/tester.txt");
o << x;
// or
// o.write( x.c_str() , x.length());
相关问题