正如我们在C ++中所知道的那样,我们拥有从istream(basic_istream)和ostream(basic_ostream)继承的class iostream。 在每一本C ++书籍中,您都可以找到,使用iostream类对象可以读取和写入同一个流。 但我真的没有看到任何解释或例子来理解为什么我应该使用这样一个奇怪的想法。 我真的不知道为什么我需要写一些流而不是从它读取:(。
我应该在需要这样的建筑时解释一下吗? 我认为使用这种构造必须有充足的理由(不要忘记,只有对于iostream声明我们使用虚拟继承和多重继承)。
此外,当我尝试编写一个简单的代码,使用fsteram(iostream的衍生物)时,我发现它不能正常工作,我期待它。 这是我的代码:
#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; }所以你能告诉我为什么这段代码可以从文件中读取而且不能写一些东西吗?
简历:请告诉我为什么我们需要class iosteram以及为什么isteram和ostream不够用以及如何使用它。
感谢和抱歉,我的英语:)。
PS可能这个问题是原始的,但请回答我。
编辑:我的代码现在工作。 感谢Murka。
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.
最满意答案
您可能想要读取和写入同一个流,因为该流执行类型转换,如std :: stringstream。 您还可以对允许读取和写入的数据源进行iostream抽象 - 例如套接字或内存缓冲区。
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.
更多推荐
发布评论