大一下c + +上机实验总目录:大一下c + +上机实验总结目录
1、建立一个包含学生学号、姓名、成绩的文本文件。要求从键盘输入一批学号、姓名和成绩,将它们存入文件中。提示:按组合键Ctrl+Z令cin输入函数返回一个0值。
参考程序:
#include<iostream>
#include <fstream>
using namespace std;
int main()
{ char fileName[30] , name[30] ; int number , score ;
ofstream outstuf ;
cout << "Please input the name of students file :\n" ;
cin >> fileName ;
outstuf.open( fileName, ios::out ) ;
if ( !outstuf )
{ cerr << "File could not be open." << endl ; return 0; }
outstuf << "学生成绩文件\n" ;
cout << "Input the number, name, and score : (Enter Ctrl-Z to end input)\n? " ;
while( cin >> number >> name >> score )
{ outstuf << number << ' ' << name << ' ' << score << '\n' ;
cout << "? " ;
}
outstuf.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() ;
}