讀一個檔inf.txt將內文中的數字全部相加起來然後再將結果輸出至outf.txt
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream qfile,afile; //qfile演程式中的Qustion afile演程式的ansfile
int theone=true; //判斷是不是第一個數字
char w; //每get一個字元放在w中
int n; //算數字
int tot=0; //算加總
qfile.open("inf.txt",ios::in);
afile.open("outf.txt",ios::out);
while(!qfile.eof())
{
n=0;
do{
qfile.get(w);
if(w>='0' && w<='9')
{
n=n*10;
n=n+(w-'0');
}
}while (w>='0' && w<='9') ;
if(n!=0)
{
tot=tot+n;
if (theone)
theone=false;
else
{
cout<<'+';
afile<<'+';
}
cout<<n;
afile<<n;
}
}
cout<<"="<<tot<<endl;
afile<<"="<<tot<<endl;
qfile.close();
afile.close();
system("pause");
return 0;
}
請先 登入 以發表留言。