一、编写程序,创建文件mul.txt,其内容为九九乘法表,其格式为:1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 2 4 6 8 10 12 14 16 18
3 .........
4 .........
5 .........
6 .........
7 .........
8 .........
9 9 18 27 36 45 54 63 72 81
要求通过循环自动生成该表,其中每个数据占4个字符位置,右对齐。实现代码:
#include<iostream> #include<fstream> #include<iomanip> #include<string> using namespace std; int main(void){ int i,j,n,count; ofstream out; out.open("mul.txt");//打开mul.txt文件 if(!out){//判读是否打开 cerr<<"can't open the file"<<endl; return -1; } out<<" ";//目的是为了对齐 for(i=1;i<10;i++)//输入到文件的第一层 1 2 3 .....9 out<<right<<setw(7)<<i; out<<endl; for(i=1;i<10;i++){ out<<i;//自第一行后,每行前的 1 2 3.....9 for(j=1;j<10;j++){//控制域宽 n=i*j; count=0; while(n){ n=n/10; count++; } out<<right<<setw(8-count)<<i*j;//计算口诀表 } out<<endl; } out.close(); }
二、用编辑器(记事本等)产生一个文本文件data.txt,其内容为若干实数,数据之间以空白字符分割。编程从该文件中读入这些实数,求出这些实数的平均值,在程序中创建并产生一个文本文件result.txt,内容为data.txt中的全体实数,每行5个数,最后一行是求出的平均值。
实现代码:
#include<iostream> #include<cstdlib> #include<ctime> #include<fstream> using namespace std; int main(void){ srand((unsigned)time(NULL));//设置随机种子,目的是每次生成的随机数不同 ofstream out1; out1.open("data.txt");//打开data.txt文件 if(!out1){//判读是否打开 cerr<<"can not open the file of data.txt!\n"; return -1; } int i; for(i=0;i<1000;i++){//随机生成1000个100以内的随机数,输入到data中 out1<<rand()%100<<" "; } out1.close();//关闭文件对象 ofstream out2; ifstream in1; int a[1000],sum=0; out2.open("result.txt");//打开result.txt if(!out2){//判读是否打开 cerr<<"can not open the file of result.txt!\n"; return -1; } in1.open("data.txt");// 打开data.txt if(!in1){//判读是否打开 cerr<<"can not open the file of data.txt!\n"; return -1; } for(i=0;i<1000;i++){//把1000个数从data流入result in1>>a[i]; out2<<a[i]<<" "; if((i+1)%5==0)//五个数据一行 out2<<endl; sum+=a[i];//求和 } out2<<sum/1000;//求平均 return 0; }
三、定义一个学生类,然后根据学生类创建一个对象,接着将该对象的数据成员的值输出到文件中,并将该数据读入到内存以检查文件的读写是否有误。
实现代码:
#include<iostream> #include<fstream> #include<iomanip> using namespace std; class student{ char name[20]; char num[20]; int age; bool initialized;//表示学生数据是否被成功读入 public: student( ){ initialized=false; } bool const data_is_ok(){ return initialized; } friend istream &operator>>(istream &in,student &x){ if(&in==&cin)//从键盘输入时给出提示 cout<<"请输入学号,姓名,年龄(以学号为'E'结束):\n"; in>>setw(11)>>x.num;//读入学号 if(in.eof()||x.num[0]=='E'){ x.initialized=false; return in; } in>>setw(9)>>x.name;//读入姓名 in>>setw(9)>>x.age;//读入年龄 x.initialized=true; return in; } friend ostream &operator<<(ostream &out,const student &x){ out<<x.num<<' ';//输出学号 out<<x.name<<' ';//输出姓名 out<<x.age<<endl;//输出年龄 return out; } }; int main(void){ ofstream out; out.open("student.txt"); if(!out){//判断是否打开 cerr<<"can not open the file!\n"; return -1; } student s; cin>>s; while(s.data_is_ok()){//判断输入是否结束 out<<s; cin>>s; } out.close(); return 0; }