C++程序设计

设计一学生注册信息登记程序,该程序要求达到以下要求:
(1)学生信息包括姓名,学号,性别;
(2)学生信息要求能够循环从键盘输入,如果输入0 0 0,则退出输入;
(3)将所有输入的学生信息按文本文件的方式存储到一名为stureginfo.txt的文件中,文件中存储信息的格式如下:
姓名:张三
学号:10521030146
性别:男
(4)停止输入后,程序读出存储到stureginfo.txt文件中的所有信息,并显示在屏幕上。

#include <iostream>
#include <string>
#include <fstream>
struct Student {
    std::string name, id, sex;
};
std::ostream& operator << (std::ostream& os, const Student& s)
{
    os << "姓名:" << s.name << std::endl
       << "学号:" << s.id << std::endl
       << "性别:" << s.sex;
    return os;
}
std::istream& operator >> (std::istream& is, Student& s)
{
    is >> s.name >> s.id >> s.sex;
    if (!is) {
        s = Student();
        std::cerr << "输入错误,停止输入" << std::endl;
    }
    return is;
}

//出题的人没吃药么…直接输出到屏幕上不就好了…还要放到文件里再读出来
std::istream& readInFile(std::ifstream& ifile, Student& s)
{
    //假设数据都是按输出格式的(没有人作死的乱改)
    std::string content;
    auto extr = [&content]()->const std::string& {
        std::string::size_type pos = content.find(':');
        content = content.substr(pos+1, 
                    content.size()-(pos+1));
        return content;
    };
    //读取姓名
    ifile >> content;
    s.name = extr();
    //读取学号
    ifile >> content;
    s.id = extr();
    //读取性别
    ifile >> content;
    s.sex = extr();
    return ifile;
}
int main()
{
    std::ofstream ofile("stureginfo.txt");
    Student s;
    while (std::cin >> s) {
        if (s.name == "0" && s.id == "0" && s.sex == "0")
            break;
        ofile << s << std::endl << std::endl;
    }
    std::ifstream ifile("stureginfo.txt");
    while (readInFile(ifile, s)) {
        std::cout << s << std::endl << std::endl;
    }
}

温馨提示:答案为网友推荐,仅供参考
相似回答