【GESP 四级】一个程序掌握大部分知识点

发布于:2025-06-30 ⋅ 阅读:(15) ⋅ 点赞:(0)

文章目录

  • 程序简介
  • 程序信息
    • 项目目录
    • 源代码
      • functions.h
      • headfile.h
      • main.cpp

程序简介

这是一个类似学生信息管理的程序,用 C++ 编写。涵盖了 GESP 四级的大部分知识点:

  • 指针的基础用法
  • 结构体的基础用法
  • try-catch的基础用法
  • <fstream>的基础用法

程序信息

项目目录

~ $ ls -a
.
..
./data.txt
./functions.h
./headfile.h
./main.cpp

源代码

functions.h

#pragma ones
#include "headfile.h"

void write_file(Student data)
{
    ofstream OutFile(PATH, ios::app);

    if (!OutFile)
    {
        throw "无法打开文件";
    }
    OutFile << data.name << data.age << data.score;

    OutFile.close();
}

void read_file(void)
{
    string name;
    int age;
    float score;
    ifstream InFile(PATH, ios::in);

    if (!InFile)
    {
        throw "无法打开文件";
    }
    cout << "姓名\t年龄\t分数" << endl;
    cout << "--------------" << endl;
    while(InFile >> name >> age >> score)
    {
        cout << name << "\t" << age << "\t" << score;
    }
    InFile.close();
}

headfile.h

#pragma ones
#include <iostream>
#include <fstream>
#include <cstdlib>
#define PATH ".\\data.txt"

using namespace std;
struct Student
{
    string name;
    int age;
    float score;
};
void write_file(Student data);
void read_file(void);

main.cpp

#include "functions.h"

int main(void)
{
    int flag;
    int n;
    string error;
    error = "输入错误"
    string *p;
    p = &error;

    cout << "请输入您需要的操作:\n1.载入数据\t2.读取数据" << endl;
    cin >> flag;
    if (flag == 1)
    {
        cout << "请输入需要载入的数据组数:";
        cin >> n;
        for (int i = 1; i <= n; i++)
        {
            Student student;
            
            cout << "姓名:";
            cin >> student.name;
            cout << "年龄:";
            cin >> student.age;
            cout << "成绩:";
            cin >> student.score;
            cout << endl;

            try
            {
                write_file(student);
            }
            catch (const char* msg)
            {
                cerr << "Error: " << msg << endl;
                return EXIT_FAILURE;
            }
            catch (...)
            {
                cerr << "Error: 未知错误。" << endl;
                return EXIT_FAILURE
            }
        }
    }
    else if (flag == 2)
    {
        try
        {
            read_file();
        }
        catch (const char* msg)
        {
            cerr << "Error: " << msg << endl;
            return EXIT_FAILURE;
        }
        catch (...)
        {
            cerr << "Error: 未知错误。" << endl;
            return EXIT_FAILURE;
        }
    }
    else
    {
        cout << *p << endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

感谢您的耐心观看!!!


网站公告

今日签到

点亮在社区的每一天
去签到