這是有關 C++ streams and File I/O
題目:流水帳管理
1.可以紀錄每筆花費金額(不用項目名稱)
2.可以讀取每筆花費金額(不用項目名稱)
3.可以計算花費的總和
目前做出一部分,我的問題是"第2點"和"第3點"
我雖然紀錄了每筆花費金額,可是當在讀取花費金額時
"我讀取的項目都只有第一筆金額,而不是所有每筆金額.."
還有,我要如何 "加總我所紀錄的每筆金額"呢?
以下是我寫的:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream fout;
ifstream fin;
int select;
int cost;
while(1)
{
cout<<"1.紀錄本次花費金額"<<endl;
cout<<"2.讀取花費金額項目"<<endl;
cout<<"3.總花費"<<endl;
cout<<"4.結束"<<endl;
cin>>select;
switch(select)
{
case 1:
fout.open("Cost.txt",ios::app); //ios::app是可以不覆蓋上次所紀錄的數字,而再新增一行。
cout<<"請輸入金額:"<<endl;
cin>>cost;
cout<<"本次輸入金額:"<<cost<<endl;
fout<<cost<<endl;
fout.close();
break;
case 2:
fin.open("Cost.txt");
fin>>cost;
cout<<"花費項目:\n"<<cost<<endl;
fin.close();
break;
case 3:
cout<<"共花費"<<cost;
break;
case 4:
exit(0);
default:
cout<<"輸入錯誤!"<<endl;
}
cout<<endl;
}
system("pause");
return 0;
}