实验题目录:
1.第一题
1、建立一个包含学生学号、姓名、成绩的文本文件。要求从键盘输入一批学号、姓名和成绩,将它们存入文件中。提示:按组合键Ctrl+Z令cin输入函数返回一个0值。
#include <bits/stdc++.h>
using namespace std;
int main()
{
ofstream out;
out.open("d://student.txt",ios::out);
if(!out)
{
cerr<<"无法打开文件"<<endl;
return 0;
}
out.setf(ios::left); //格式控制
out.width(20);
out<<"学生姓名";
out.width(20);
out<<"学号";
out.width(20);
out<<"学生成绩"<<endl;
string name,id,grade;
while(cin>>name>>id>>grade)
{
out.width(20);
out<<name;
out.width(20);
out<<id;
out.width(20);
out<<grade<<endl;
}
out.close();
return 0;
}
2.第二题
有一个文本文件D:\student.txt,里面存储内容如下所示:
This is a file of students.
101 陈光明 85
102 王丽 90
103 郭小兰 76
104 彭文 65
105 李立 78
.......
.......
要求读此文本文件内容,在屏幕显示学生记录,以及最高分数、最低分数和平均分数。提示:从文件读内容,遇到文件结束符时,返回0;注意文件第一行的干扰,可以把文件中第一行内容读取后,再对文件内容,即成绩进行处理;读取第一行内容可以使用如下两个函数中的任意一个:
两个无格式化提取操作成员函数:
istream & istream :: get ( char * , int , char = '\n' ) ;
istream & istream :: getline ( char * , int , char = '\n' ) ;
作用:从文本中提取指定个数的字符,并在串数组末添加一个空字符'\0'
#include<iostream>
#include <fstream>
using namespace std;
int main()
{ char name[30] , s[80] ;
int number , score ; int n = 0, max, min, total = 0 ; double ave;
ifstream instuf( "d:\\students.txt", ios::in ) ;
if ( !instuf )
{ cerr << "File could not be open." << endl ; abort(); }
instuf.getline( s, 80 ) ;
while( instuf >> number >> name >> score )
{ cout << number << '\t' << name << '\t' << score << '\n' ;
if (n==0) { max = min = score; }
else { if ( score > max ) max = score ;
if ( score < min ) min = score ; }
total+=score; n++;
}
ave = double(total) / n ;
cout << "maximal is : " << max << endl << "minimal is : " << min << endl<< "average is : ” << ave << endl;
instuf.close() ;
}