问题
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