As we know in C++ we have class iostream, which is inherited from istream(basic_istream) and ostream (basic_ostream). In every C++ book you can find, that with iostream class object you can read and write to the same stream. But I realy haven’t see any explanation or example to understand why should I use such a strange think. I really don’t know why should I need to write to some stream and than read from it :(.
Could you explain me when I should need such construction? I think there must be serous reason for using such construction(don’t forget that only for iostream declaration we are using virtual inheritance and multiple inheritance).
Also when I try to write a simple code, which is using fsteram(derivative of iostream) I find, that its not working in way, which I expect. Here is my code:
#include <fstream>
using namespace std;
int main()
{
fstream fstr("somefile.txt",fstream::in|fstream::out);//fstream is deriveted from iosteram
int n;
fstr>>n;//reading n (WORKS FINE !!!).
fstr.flush();
//trying to print Hello to the same file
fstr<<"Hello"<<endl;// NOT WORKING!!!!!!!
fstr.flush();
return 0;
}
So could you tell me why this code can read from file and can’t write something to it????
Resume:
Please tell me why we need class iosteram and why isteram and ostream arn’t enought and how to use it.
Thanks and sorry for my english :).
P.S. Probably this question is to primitive, but please answer me.
Edit: My code is now working. Thanks to Murka.
You might want to read from and write to the same stream because the stream performs type conversions, like std::stringstream. You could also have iostream abstractions over data sources that permit both reading and writing- such as a socket or an in-memory buffer.