我对ofstream有点迷惑。从ostream继承的ofstream。它还继承了ostream的"operator<<“方法。
ofstream x;
x << "hello world" << endl;
//cout << "hello world" << endl;
system("pause");
return 0;上面的代码片段尝试使用ofsream的对象向终端输出"hello world“,就像cout所做的那样。
上面的代码片段可以编译,但没有显示任何内容。为什么会发生这种情况?
谢谢,
发布于 2012-06-16 12:50:14
已经很长一段时间了,但是流的IIRC是一个output_ file -stream,它将数据流式传输到打开的文件中。为了让ofstream对象真正打印到终端,您必须使其打开"/dev/console“或类似的东西。ofstream的普通实例可能无法打开/dev/console b/c您已经有可用的cout。
发布于 2012-06-16 12:47:11
ofstream是文件对象的抽象。为了能够创建文件,您需要传入文件的名称。如果不这样做,就会创建一个默认的ofstream对象(这就是它编译的原因)。就其本身而言,这样的对象没有多大用处。尝试:
ofstream x( "out.txt" );
x << "hello world" << endl;
...发布于 2012-06-16 13:15:06
http://en.wikipedia.org/wiki/Input/output_%28C%2B%2B%29
<iostream> contains the definition of basic_iostream class template,
which implements formatted input and output
<fstream> contains the definitions of basic_ifstream, basic_ofstream and
basic_fstream class templates which implement formatted input, output and input/output
on file streams.https://stackoverflow.com/questions/11060874
复制相似问题