gpt4 book ai didi

c++ - ofstream的使用

转载 作者:太空宇宙 更新时间:2023-11-04 12:08:10 25 4
gpt4 key购买 nike

我对 ofstream 有点困惑。ofstream 继承自 ostream。而它还继承了方法“operator<<”ostream。

    ofstream x;
x << "hello world" << endl;
//cout << "hello world" << endl;

system("pause");
return 0;

上面的代码片段试图使用 ofsream 的一个对象像 cout 一样向终端输出“hello world”。

上面的代码片段可以编译但什么也没有显示。为什么会这样?

谢谢,

最佳答案

ofstream 是文件对象的抽象。为了能够创建文件,您需要传入文件名。如果你不这样做,就会创建一个默认的 ofstream 对象(这就是它编译的原因)。就其本身而言,这样的对象并没有多大用处。尝试:

ofstream x( "out.txt" );
x << "hello world" << endl;

...

关于c++ - ofstream的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11060874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com