gpt4 book ai didi

c++ - 我应该在哪里使用 iostream 类?

转载 作者:太空狗 更新时间:2023-10-29 20:18:18 28 4
gpt4 key购买 nike

正如我们所知,在 C++ 中我们有类 iostream,它继承自 istream(basic_istream) 和 ostream (basic_ostream)。在每本 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;
}

那么你能告诉我为什么这段代码可以从文件中读取而不能向其中写入内容吗????

简历:请告诉我为什么我们需要 iosteram 类,为什么 isteram 和 ostream 不够用以及如何使用它。

谢谢,对不起我的英语:).

附言可能这个问题太原始了,但请回答我。

编辑:我的代码现在可以工作了。感谢穆尔卡。

最佳答案

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;
}

关于c++ - 我应该在哪里使用 iostream 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4553785/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com