第七章作业

来源:互联网 发布:葫芦线切割3b编程实例 编辑:程序博客网 时间:2024/05/16 15:08
第一题
#include <iostream>#include <fstream>#include <cctype>using namespace std;void main(){fstream file;char ch;file.open("test.txt",ios::out);char s[20];cout<<"输入一段最多为19个字符的话语:直到输入为cirl+x结束:"<<endl;cin>>s;file<<s;//可以用<<输出到文件中file.close();int letters=0;file.open("test.txt",ios::in);while(!file.eof()){//cout<<"111"<<endl;ch=file.get();if(isalpha(ch))letters++;}file.close();cout<<"the number of letters is"<<letters<<endl;}

第二题
#include <iostream>#include <fstream>using namespace std;char charGet(istream&in=cin){char ch=cin.get();while(ch=='\n'||ch==' '||ch=='\t')ch=cin.get();return ch;}struct Student{int num;double grade;char name[16];};int main(){Student student;char ch;fstream file;int num=0;file.open("学生.txt",ios::out|ios::binary);file.close();file.open("学生.txt",ios::out|ios::in|ios::binary);if(file.fail()){cout<<"打开文件失败!"<<endl;exit(0);}cout<<"是否继续输入,是的话请输入‘y’:";while((ch=charGet())=='y'){num++;cout<<"学生的学号:";cin>>student.num;cout<<"学生的姓名:";cin>>student.name;cout<<"学生的成绩:";cin>>student.grade;file.write((char *)&student,sizeof(student));//write和read只能写二进制文件cout<<"是否继续输入,是的话请输入‘y’:";}Student s;for(int i=0;i<num;i++){file.seekg(i*sizeof(s));//file.seekg(i*sizeof(s),ios::beg);file.read((char *)&s,sizeof(s));cout<<"学生学号:"<<s.num<<endl;cout<<"学生姓名:"<<s.name<<endl;cout<<"学生成绩:"<<s.grade<<endl;}file.close();system("PAUSE");return 0;}

第三题
#include <iostream>#include <fstream>using namespace std;char charGet(){char ch=cin.get();while(ch==' '||ch=='\t'||ch=='\n')ch=cin.get();return ch;}struct Worker{char name[16];float wage;int num;};void main(){fstream file;file.open("worker.txt",ios::out|ios::binary);file.close();file.open("worker.txt",ios::out|ios::in|ios::binary);if(file.fail()){cout<<"打开文件失败!"<<endl;exit(0);}int num=0;char ch;Worker worker;cout<<"if data needs to be inputed,please input 'y':";while((ch=charGet())=='y'){num++;cout<<"the num of worker:";cin>>worker.num;cout<<"the name of worker:";cin>>worker.name;cout<<"the wage of worker:";cin>>worker.wage;file.write((char *)&worker,sizeof(worker));cout<<"if data needs to be inputed,please input 'y':";}for(int i=0;i<num;i++){file.seekg(i*sizeof(worker));file.read((char *)&worker,sizeof(worker));cout<<"the num of worker:";cout<<worker.num<<endl;cout<<"the name of worker:";cout<<worker.name<<endl;cout<<"the wage of worker:";cout<<worker.wage<<endl;}file.close();system("PAUSE");}

0 0