顯示具有 吸普拉斯 標籤的文章。 顯示所有文章
顯示具有 吸普拉斯 標籤的文章。 顯示所有文章

星期日, 8月 26, 2007

C++檔案讀取&存檔

/*
請寫一程式讀入rand.txt內的1000個數值,
算出這1000個數值的平均值,顯示於screen上
*/
#include
#include
#include
#include
#include
using namespace std;
int main(void)
{
  int count=0 ;
  char temp,test[4],n;
  double final,sum=0,i;
  ifstream ifile("d:\\rand.txt",ios::in);
  if(ifile.is_open())
{
  while(ifile.getline(test,4)!='\0')
{
  i=atoi(test); //文字陣列轉int
  sum=sum+i;
  count+=1;
}
  cout<<"平均數為"<<sum/count<<endl;

}
else
  cout <<"檔案開啟失敗..." <<endl;
  ifile.close();
   system("pause");
   return 0;
}
=========================
/*
合併A檔,B檔成為C檔

*/
#include
#include
#include
using namespace std;
int main(void)
{
  char txt[80];
  ifstream ifile1("d:\\aaa.txt",ios::in);
  ifstream ifile2("d:\\bbb.txt",ios::in);
  ofstream afile3("d:\\ccc.txt",ios::app);

  while(!ifile1.eof()) // 判別是否讀到檔案的尾端
  {
   ifile1.getline(txt,80,'\n');
   afile3 <<txt <<endl; }

  while(!ifile2.eof())  // 判別是否讀到檔案的尾端
  {
    ifile2.getline(txt,80,'\n');
   afile3 << txt <<endl;
  }
  cout << "已將檔案合併..." <<endl;
system("pause");
return 0;
}


讀檔:
ex1.
while(ifile.getline(test,4)!='\0')

ex2.
while(ifile.get(ch)!='\0')
txt[n++]=ch;

Function Template

/*
請使用function template的功能,

寫出名為cubic的樣板函式
他的功能是算出數入數值的立方,
並以完整程式驗證
分別輸入int,float,double 3種資料type的數值
*/
Ex 1:
template <class T>
T cubic(T a)
{
return a*a*a;
}

====>>cubic(變數)

Ex 2:
template <class T,class T2>
double times(T a,T2 b) //T ==> double
{
double sum=a*b;
return sum;
}
===>>times(變數a,變數b)