Amber_yib 2020-05-24 11:02 采纳率: 100%
浏览 854
已采纳

C++读文件创建链表问题

请大家看看这道题应该怎么写呢?

C++期末成绩存放在文本文件 “Score.txt”中,要求编写程序读取该文本文件创建链表,并在链表上根据学号查找姓名和成绩。

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

  • 写回答

1条回答

  • threenewbee 2020-05-24 13:34
    关注

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

    // Q1077615.cpp : Defines the entry point for the console application.
    //
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>
    #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;
        FILE * fp = fopen("Score.txt", "r+");
        while (true)
        {
            unsigned long id;
            char name[100];
            float score;
            if (fscanf(fp, "%ld,%[^,],%f", &id, name, &score) == EOF) break;
            p->next = new student;
            p = p->next;
            p->next = NULL;
            p->id = id;
            p->name = name;
            p->score = score;
        }
        int n;
        while (1)
        {
            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 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿