一、 程式設計序
1. 將10個數輸入到檔案at1.dat中。
程式如下:
#include
#include
using namespace std;
int main( )
{int a,i;
ofstream outfile("at1.dat",ios::out);
for(i=0;i<10;i++)
{ cin>>a;
}
outfile.close( );
return 0;
}
1. 將檔案at1.dat中的資料讀入,計算每個數的平方,學術期刊,並依次存放到檔案at2.dat中。
程式如下:
#include
#include
using namespace std;
int main( )
{int a,i;
ifstream infile("at1.dat",ios::in);
ofstream outfile("at2.dat",ios::out);
for(i=0;i<10;i++)
{ infile>>a;
}
outfile.close( );
infile.close();
return 0;
}
2. 將一批資料以二進位制形式存放在磁碟檔案中。
程式如下:
#include
#include
using namespace std;
int main()
{int a,i,n;
ofstream outfile("f.dat",ios::out ios::binary);
cout<<"請輸入資料個數:99期刊";
cin>>n;
for(i=0;i
{ cin>>a;
outfile.write((char *)&a,4);
}
outfile.close();
return 0;
}
二、 改錯
1. 檔案dy.dat中有一批非負整數,要求將dy.dat中的偶數挑出來,寫到檔案ot.dat中。指出程式中有錯的地方,並改正。
#include
using namespace std;
int main( )
{int b;
ifstream infile,outfile;
infile.open("dy.dat");
outfile.open("ot.dat");
infile>>b;
while(b>=0)
{ if(b%2==0) outfile<
infile>>b;
}
infile.close( );
outfile.close( );
return 0;
}
正確程式:
#include
#include
using namespace std;
int main( )
{int b;
ifstream infile;
ofstream outfile;
infile.open("dy.dat");
outfile.open("ot.dat",ios::out);
infile>>b;
while(b>=0)
{ cout<
if(b%2==0) outfile<
infile>>b;
}
infile.close( );
outfile.close( );
return 0;
}
2. 從鍵盤輸入五個整數,將其用二進位制形式寫入到檔案f.dat中,期刊發表,然後將這五個數從檔案中讀出,並在顯示器上輸出。
#include
#include
using www.99qk.com namespace std;
int main()
{int a,i;
ofstream outfile("f.dat",ios::out ios::binary);
for(i=0;i<5;i++)
{ cin>>a;
outfile.write((char *)&a,4);
}
outfile.open("f.dat",ios::in ios::binary);
for(i=0;i<5;i++)
{ outfile.read((char *)&a,4);
}
return 0;
}
正確程式:
#include
#include
using namespace std;
int main()
{int a,i;
ofstream outfile("f.dat",ios::out ios::binary);
ifstream infile("f.dat",ios::in ios::binary);
for(i=0;i<5;i++)
{ cin>>a;
outfile.write((char *)&a,4);
}
outfile.close();
for(i=0;i<5;i++)
{ infile.read((char *)&a,4);
}
infile.close();
return 0;
}