c++ - Ofstream 效果不佳?

标签 c++ file fstream

在这段代码中,fout 是一个 ofstream 对象,它应该写入一个名为 output.txt 的文件。由于某种原因 output.txt 总是空的!。我会问我在代码中犯的错误:

#include<iostream>
#include<fstream>
#include<stdio.h>//to pause console screen
using namespace std;

double Volume(double);

int main() {
    ifstream fin; //read object
    ofstream fout;// writing object
    double Radius;
    fin.open("input.txt");
    fout.open("output.txt");
    if(!fin){
        cout<<"There a problem, input.txt can not be reached"<<endl;
    }
    else{
fin>>Radius;
fout<<Volume(Radius);
cout<<"Done! check output.txt file to see the sphare volume"<<endl;
    }

    getchar();//to pause console screen
return 0;
}

double Volume(double r){

double vol;
vol= (4.0/3.0)*3.14*r*r*r;
return vol;
}

最佳答案

“output.txt 总是空的”

我怀疑你不允许 fout刷新它的输出。这些说法是否适用于您?

  • getchar()之后检查“output.txt”的内容是 调用,但在程序结束之前?

  • 您使用 Ctrl+C 结束程序?

如果是这样,您还没有允许将数据写入fout .您可以通过避免这两种情况或执行以下操作之一来解决此问题:

  • 添加fout << endl在你写入数据之后,或者

  • 添加fout << flush在你写入数据之后,或者

  • 添加fout.close()写入数据后。

关于c++ - Ofstream 效果不佳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8332715/

相关文章:

C++ 如何在类函数中构造一个对象,执行一些操作并返回值?

c++ - 从 .dat 文件读取参数到 C++?

python - python 关联文件中的项目

c++ - 如何在 C++ 中使用 ',' 作为 getline 分隔符

c++ - Xcode5:链接 aws4c 库

c++ - 如何在 C++ 中使用一定数量的空格打印输出

c++ - 虚基类在多级继承中有什么用?

c++ - seekp()、seekg()、read() 和 write() 在同一个文件上的问题

c++ - vector<char> 到 int 与 vector<wchar_t> 到 int

c++ - 我需要在写入后和读取前关闭文件吗?