IO流与文件操作
一、填空
1-1 使用提取符(<<)可以输出各种基本数据类型的变量的值,也可以输出指针值。 T
1-2 预定义的插入符从键盘上接收数据是不带缓冲区的。 F
1-3 The cin stream normally is connected to the display screen. F
1-4 这是一个判断题的样例。答案为T,分值为5分。 T
二、选择
2-1 cout 是由I/O 流库预定义的( )。 B
A 类
B 对象
C 包含文件
D 常量
2-2 分析以下程序:程序的输出结果是 B
#include <iostream>
using namespace std;
void fun(int num)
{
cout << num << endl;
}
void fun(char ch)
{
cout << (ch + 1) << endl;
}
int main()
{
fun('A');
return 0;
}
A 65
B 66
C A
D B
2-3 下列关于cin和cout的说法中,错误的是__D__。
A cin用于读入用户输入的数据
B cout用于输出数据
C cin比C语言中的scanf()函数更有优势,它可以读取空格
D cout通常与<<运算符结合
三、函数题
6-1 学生成绩的输入和输出(运算符重载) (10分)
现在需要输入一组学生的姓名和成绩,然后输出这些学生的姓名和等级。
输入时,首先要输入学生数(正整数)N。接着输入N组学生成绩,每组成绩包括两项:第一项是学生姓名,第二项是学生的成绩(整数)。
输出时,依次输出各个学生的序号(从1开始顺序编号),学生姓名,成绩等级(不小于60为PASS,否则为FAIL)
函数接口定义:
面向Student类对象的流插入和流提取运算符
裁判测试程序样例:
#include <iostream>
#include <string>
using namespace std;
/* 请在这里填写答案 */
int main(){
int i, repeat;
Student st;
cin>>repeat;
for(i=0;i<repeat;i++){
cin>>st;
cout<<st<<endl;
}
return 0;
}
输入样例:
3
Li 75
Zhang 50
Yang 99
输出样例:
- Li PASS
- Zhang FAIL
- Yang PASS
class Student
{
public :
Student ( string ,int);
friend istream & operator >>(istream&,Student &);
friend ostream & operator <<(ostream&,Student &);
private:
string name;
int score;
};
Student::Student( string name="def",int score=0){}
istream &operator >>(istream & is ,Student &s )
{
is>> s.name>>s.score;
return is;`在这里插入代码片`
}
ostream &operator <<(ostream & os ,Student &s)
{
static int sum;sum=sum+1;
os<<sum<<". "<<s.name<<" ";
if(s.score>=60)
os<<"PASS";
else
os<<"FAIL";
return os;
}
6-2 对学生对象按照成绩升序排序 (10分)
下面这段代码要实现对学生对象按照成绩升序排序。 仔细阅读代码,要求实现编程实现输出运算符“<<”和小于“<”运算符,使本程序能完成预定的排序功能。
裁判测试程序样例:
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Student {
string name;
char sex;
int score;
string grade;
public:
Student(string name, char sex, int score, string grade);
friend ostream &operator<< (ostream& os, Student st) ;
friend bool operator<(Student &st1, Student &st2);
};
//你提交的代码将被嵌入到这里
Student::Student(string name, char sex, int score, string grade) {
this->name = name;
this->sex = sex;
this->score = score;
this->grade = grade;
}
int main() {
list<Student> st;
string name, grade;
char sex; int score;
for(int i = 0; i < 5; i++) {
cin>>name; cin>>sex;
cin>>score; cin>>grade;
st.push_back(Student(name, sex, score, grade));
}
st.sort();
list<Student>::iterator p = st.begin();
while(p != st.end()) {
cout<<*p;
p++;
}
return 0;
}
输入样例:
Bill M 86 JK1501
David M 98 JK1502
Mary F 78 JK1503
Adam M 83 JK1504
Rose F 96 JK1505
输出样例:
Mary F 78 JK1503
Adam M 83 JK1504
Bill M 86 JK1501
Rose F 96 JK1505
David M 98 JK1502
ostream &operator<< (ostream& os, Student st)
{
os << st.name << " " << st.sex << " " << st.score << " " << st.grade << endl;
}
bool operator < (Student &st1, Student &st2)
{
if(st1.score < st2.score)
return true;
return false;
}