《C++编程这样学》第十四章:文件操作- 加油站题解

1. 单词的长度

【问题描述】

编写程序,从word.in文件中读入多个单词,文件中每行一个单词,直到读到文件结束为止,在word.out文件中保存各个单词的长度。

【题解代码】
#include <iostream>
using namespace std;

int main()
{
    freopen("word.in","r",stdin);
    freopen("word.out","w",stdout);
    string s;
    while (cin >> s)
    {
        cout << s.size() << endl;
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}

2. 按成绩排序

【问题描述】

编写程序,从score.in文件中读入多名学生的姓名和分数,将读入的信息按分数由高到低排序后保存到score.out文件中。

【题解代码】
#include <iostream>
#include <algorithm>
using namespace std;

struct Node {
    string name;
    int score;
    bool operator < (const Node &x) const {
        if (score == x.score) {
            return name < x.name;
        }
        return score > x.score;
    }
}a[1010];

int main()
{
    freopen("score.in","r",stdin);
    freopen("score.out","w",stdout);
    int n;
    cin >> n;
    for (int i = 0; i < n; i ++)
    {
        cin >> a[i].name >> a[i].score;
    }
    sort(a, a+n);
    for (int i = 0; i < n; i ++)
    {
        cout << a[i].name << " " << a[i].score << endl;
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值