文件输入和输出练习题

本篇博客涉及文件输入输出的练习,包括创建学生类对象,从键盘接收输入并将其信息存储到data.txt文件中,以及读取文件内容显示学生数据及对应的分数等级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#文件输入和输出练习题
有一个学生类Student,属性有学号、姓名、成绩。
1.需要从键盘上输入一系列学生类对象,并将这些学生信息写入文件data.txt中。
2.显示文件data.txt中的学生数据和相应的成绩等级

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
class Student
{
private:
    int number;
    string name;
    double score;
public:
    void mark();
    friend istream & operator >>(istream &,Student &);
    friend ostream & operator <<(ostream &,Student &);
};

void Student::mark()
{
    if(score>=90)
        cout<<setw(10)<<"优\n";
    else if(score>=80)
        cout<<setw(10)<<"良\n";
    else if(score>=70)
        cout<<setw(10)<<"中\n";
    else if(score>=60)
        cout<<setw(10)<<"及格\n";
    else
        cout<<setw(10)<<"不及格\n";
}
istream & operator>>(istream & in,Student & s)
{
    cout<<"请依次输入学生的学号、姓名、成绩:\n";
    in>>s.number>>s.name>>s.score;
    return in;
}
ostream & operator<<(ostream & out,Student & s)
{
    out<<s.number<<setw(6)<<s.name<<setw(6)<<s.score;
    return out;
}

int main()
{
    int n;
    ofstream fout("/Users/用户名/Desktop/data.txt",ios::out);//Xcode要写明路径
    if(!fout)
    {
        cerr<<"open file error!"<<endl;
        exit(1);
    }
    cout<<"请输入总人数:\n";
    cin>>n;
    Student *pstu=new Student[n+1];
    for(int i=0;i<n;i++)
    {
        cin>>pstu[i];
    }
    cout<<"--------------------"<<endl;
    for(int i=0;i<n;i++)
    {
        cout<<pstu[i];
        pstu[i].mark();
        fout<<pstu[i]<<endl;
    }

    fout.close();
    
    return 0;
}

输出:

请输入总人数:
3
请依次输入学生的学号、姓名、成绩:
171 Lily 100
请依次输入学生的学号、姓名、成绩:
172 Leo 80
请依次输入学生的学号、姓名、成绩:
173 Amy 70
--------------------
171  Lily   100      优
172   Leo    80      良
173   Amy    70      中
Program ended with exit code: 0

txt文件:

//data.txt
171  Lily   100
172   Leo    80
173   Amy    70
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值