m0_48121319 2020-05-25 23:31 采纳率: 0%
浏览 642

C++如何读取文件创建链表,用ifstream和ofstream来做?

各位大佬,麻烦看看这题怎么做?
C++期末成绩存放在文本文件 “Score.txt”中,要求编写程序读取该文本文件创建链表,并在链表上根据学号查找姓名和成绩。

文本文件的各列之间使用空格分隔,文件行数不确定。
**要求使用ifstream类和ofstream类的对象读取和写入数据**。
链表的一个结点可声明如下:
struct student
{
unsigned long id;
string name;
float score;
student *next; //下一个结点的指针
}
循环从键盘读入学号,查询对应的姓名和成绩,输入学号为0时退出循环。

  • 写回答

2条回答 默认 最新

  • threenewbee 2020-05-26 00:41
    关注

    如果问题得到解决,请点下采纳

    // Q1077615.cpp : Defines the entry point for the console application.
    //
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    using namespace std;
    struct student 
    {
        unsigned long id;
        string name;
        float score;
        student *next; //下一个结点的指针
    };
    
    int main()
    {
        student head = {-1,"",0};
        head.next = NULL;
        student * p = &head;
        ifstream in("Score.txt");
        while (true)
        {
            unsigned long id;
            char name[100];
            float score;
            string line;
            if (!getline(in, line, '\n')) break;
            stringstream ss(line);
            p->next = new student;
            p = p->next;
            p->next = NULL;
            ss >> id;
            ss >> name;
            ss >> score;
        }
        int n;
        while (true)
        {
            cin >> n;
            if (n == 0) break;
            p = head.next;
            while (p)
            {
                if (p->id == n)
                {
                    cout << p->name << " " << p->score << endl;
                    break;
                }
                p = p->next;
            }
            if (!p || p->id != n)
                cout << "no record!" << endl;
        }
        return 0;
    }
    
    
    210871,张三,95
    210872,lisi,92.5
    210873,jim zhao,97
    210874,han meimei,100
    210875,孙行者,80
    210876,tony,80
    210877,铁柱,94.5
    210878,小明,98
    

    图片说明

    完整代码下载
    https://download.csdn.net/download/caozhy/12453617

    评论

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛