第七章作业

第一题
#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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值