在这段代码中,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/