#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
struct Student {
    string name;
    int age;
};

void WriteDataToFile() {
    std::vector<Student> students = {{"John", 20}, {"Emily", 22}, {"Michael", 21}};

    std::ofstream file("students.dat");
    if (!file) {
        std::cout << "无法打开文件!" << std::endl;
        return;
    }

    for (const auto& student : students) {
        file << student.name << " " << student.age << std::endl;
    }

    file.close();
}

void ReadDataFromFile() {
    std::vector<Student> students;

    std::ifstream file("students.dat");
    if (!file) {
        std::cout << "无法打开文件!" << std::endl;
        return;
    }

    std::string line;
    while (std::getline(file, line)) {
        std::istringstream iss(line);
        std::string name;
        int age;

        iss >> name >> age;
        students.push_back({name, age});
    }

    file.close();

    for (const auto& student : students) {
        std::cout << "姓名: " << student.name << "  年龄: " << student.age << std::endl;
    }
}

int main() {
    int choice;

    while (true) {
        std::cout << "输入1选择写入,输入2选择读取:";
        std::cin >> choice;

        if (choice == 1) {
            WriteDataToFile();
            std::cout << "数据已写入文件!" << std::endl;
            break;
        } else if (choice == 2) {
            ReadDataFromFile();
            break;
        } else {
            std::cout << "无效的选择!" << std::endl;
        }
    }

    return 0;
}

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐