usage of ofstream

て烟熏妆下的殇ゞ 提交于 2019-12-11 04:52:33

问题


I'm kind of confused by ofstream. ofstream inherited from ostream. And it also inherited method "operator<<" from ostream.

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

    system("pause");
    return 0;

The above code clip is trying to use an object of ofsream to output "hello world" to the terminal just as cout did.

The above code clip can compile but shows nothing. Why does it happen?

Thanks,


回答1:


It's been a long time, but IIRC of stream is an output_file-stream which streams data into an opened file. For an ofstream object to actually print to the terminal you would have to make it open "/dev/console" or something similar. A plain instance of ofstream probably doesnt open /dev/console b/c you already have cout available.




回答2:


ofstream is an abstraction for a file object. In order to be able to create a file, you need to pass in the file's name. If you don't a default ofstream object is created (which is why it compiles). By itself, such an object isn't of much use. Try:

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

...



回答3:


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/usage-of-ofstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!