Where should I use the iostream class?

As is known in C ++, we have the iostream class, which is inherited from istream (basic_istream) and ostream (basic_ostream). In every C ++ book you can find that with an iostream class object you can read and write to the same stream. But I really do not see any explanation or examples to understand why I should use such a strange opinion. I really don’t know why I need to write to some stream and how to read from it :(.

Could you explain to me when I need such a design? I think that there must be a serious reason for using this design (do not forget that only for iostream declaration we use virtual inheritance and multiple inheritance).

Also, when I try to write simple code that uses fsteram (derived from iostream), I find that it does not work in the path that 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 a file and cannot write something?

Summary: Please tell me why we need the iosteram class and why isteram and ostream arn't enought and how to use it.

Thanks and sorry for my english :).

PS This question is probably primitive, but please answer me.

Edit: my code now works. Thanks Murka.

+3
source share
4 answers

, , , std:: stringstream. iostream , , , , .

+1

IIRC , , , . , .

#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.clear();     //Clear any errors, eof, etc.
    fstr.seekg(0, ios::beg);  //Seek to beginning of file
    fstr.flush();

    //trying to print Hello to the same file
    fstr<<"Hello"<<endl;// NOW WORKS!!!

    fstr.flush();

    return 0;
}
+4

?

, , : , , , ​​ , () .

+2

when will I need such a design

Rarely. See my answer here: https://stackoverflow.com/questions/4517299/is-fstream-better-than-iostream-in-c/4517883#4517883

Edited: If you don’t think you need it, you don’t need it.

0
source

Source: https://habr.com/ru/post/1782576/


All Articles