Ofstream 效果不好?
在此代码中,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;
}
In this code, fout is an ofstream object, It supposes to write to a file called output.txt
. For a reason output.txt
always empty!. I would ask about the mistake I did in the code :
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
“output.txt 始终为空”
我怀疑您不允许
fout
刷新其输出。这些陈述中的任何一个适用于您吗?在
getchar()
之后检查“output.txt”的内容调用,但在程序结束之前?
你用Ctrl+C结束程序?
如果是这样,则您不允许将数据写入
fout
。您可以通过避免这两种情况或执行以下操作之一来解决此问题:Add
fout << endl
写入数据后,或添加
fout <<写入数据后刷新
,或添加
fout.close()
。"output.txt always empty"
I suspect that you are not allowing
fout
to flush its output. Do either of these statements apply to you?You check the contents of "output.txt" after the
getchar()
isinvoked, but before the program ends?
You end the program with a Ctrl+C?
If so, you have not allowed the data to be written to
fout
. You can solve this problem by avoiding those two conditions, or doing one of these:Add
fout << endl
after you write your data, orAdd
fout << flush
after you write your data, orAdd
fout.close()
after you write your data.你必须刷新流,在完成输出后调用
fout.flush()
,你所做的就是构建一个尚未写入文件的缓冲区。flush
实际上将缓冲区放入文件中。You have to flush the stream, call
fout.flush()
after you are done outputting, all you are doing is building a buffer that has yet to be written to the file.flush
actually puts the buffer into the file.除了调用
fout.flush()
之外,您还可以将: 更改为
: 或者如果不再需要,也可以关闭流
fout.close()
。In addition to calling
fout.flush()
you could change:to
or you can close the stream
fout.close()
if it is no longer required.