简答题 C++
题号 #2657833

定义一个Student类,其中含学号、姓名、成绩数据成员。建立若干个Student类对象,将它们保存到文件Record.dat中。然后显示文件中的内容。

进入在线模考

参考答案

暂无

答案解析

#include <iostream.h>
#include <string.h>
#include <fstream.h>
//using namespace std;
class Student{
    char Id[10];
    char Name[10];
    int Score;
public:
    Student();
    Student(char *id,char *name,int score);
    Student(Student &s);
    ~Student();
    friend ostream& operator<<(ostream&,Student&);
};
Student::Student(){
    strcpy(Id,"00000000");
    strcpy(Name,"noname");
    Score=-1;
}
Student::Student(char *id,char *name,int score){
    strcpy(Id,id);
    strcpy(Name,name);
    Score=score;
}
Student::Student(Student &s){
    strcpy(Id,s.Id);
    strcpy(Name,s.Name);
    Score=s.Score;
}
Student::~Student(){}
ostream& operator<<(ostream& out,Student& stu){
    out<<stu.Id <<'\t'<<stu.Name <<'\t'<<stu.Score <<endl;
    return out;
}
int main(){
    int i;
    Student stu[5]={Student("08142301","zhang",80),Student("08142302","Li",100),
        Student("08142304","sun",80),Student("08142308","qian",40),Student("08142311","wang",100)};
    Student s1[5];
    ofstream ostu;
    ifstream istu;
    ostu.open("d:\\student.dat",ios::out||ios::binary);
    for(i=0;i<5;i++)
        ostu.write((char*)&stu[i],sizeof(Student));
    ostu.close();
    istu.open("d:\\student.dat",ios::in||ios::binary);
    for(i=0;i<5;i++){
        istu.read((char*)&s1[i],sizeof(Student));
        cout<<s1[i];
    }
    istu.close();
    return 0;
}

你可能感兴趣的试题

A.C++是C语言的超集    
B.C++对C语言进行了扩充
C.C++包含C语言的全部语法特征   
D.C++与C语言都是面向对象的程序设计语言
A.继承性   
B.功能分解,逐步求精   
C.封装性和信息隐藏   
D.多态性
找试题 · 找答案 · 找资料 在线模考