实现此代码时
并且程序在黑屏弹出时运行它没有其他等待一段时间没有发生没有完成没有给我进程返回0知道它完成输出文件是空的如果有人可以告诉我有什么问题这里
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
int main()
{
ifstream file;
ofstream out;
file.open("coinsCoint.txt");
out.open("1234567.txt");
int pennis,nickle,dime,quarter,sum=0;
float total;
while(!file.eof())
{
file >> pennis >> nickle >> dime >> quarter;
sum+=pennis+nickle*5+dime*10+quarter*25;
total=sum/100.0;
}
out << "Total amount collected is: $" << fixed << showpoint <<
setprecision(2) << total;
file.close();
out.close();
return 0;
}
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
int main()
{
ifstream file;
ofstream out;
file.open("coinsCoint.txt");
int pennis = 0, nickle = 0, dime = 0, quarter = 0, sum = 0;
float total = 0.0;
/* check if file is opened */
if (file.is_open()){
while (!file.eof())
{
file >> pennis >> nickle >> dime >> quarter;
cout << "pennis " << pennis << endl;
cout << "nickle " << nickle << endl;
cout << "dime " << dime << endl;
cout << "quarter " << quarter << endl;
sum += pennis + nickle * 5 + dime * 10 + quarter * 25;
total = sum / 100.0;
cout << "total " << total;
}
file.close();
}
/* return if error in file open */
else {
cout<< "can not open given file";
return 0;
}
out.open("1234567.txt");
if (out.is_open()){
out << "Total amount collected is: $" << fixed << showpoint <<
setprecision(2) << total;
out.close();
}
return 0;
}
类似的教程https://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/io/readtextfile.html
您应该始终检查文件是否已由is_open()
正确打开
您需要使用cout <<
打印以控制“黑屏”
该文件看起来像
1
2
3
4
输出应该是这样的
pennis 1
nickle 2
dime 3
quarter 4
total 1.41Press <RETURN> to close this window...