Fstream不会保存文件中的最后一个单词,也不会从文件中读取

Fstream doesnt save the last word in the file and it doesnt read from the file, too

本文关键字:读取 文件 最后一个 保存文件 Fstream 单词      更新时间:2023-10-16

这是一个在文件中注册游戏的简单代码,但有两个问题。

首先,参数或属性"classification"没有保存在文件中。

第二,当我从文件中读取时,内容不会显示。

在评论之前,你必须知道这是我第一次使用文件,我正在努力自学。

我知道这段代码缺乏模块性,我应该声明一个对象的指针向量,而不是指向对象,或者我应该声明智能指针,但我只是想向你展示我在文件中遇到的问题。

非常感谢任何帮助

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using std::string;
using std::cout;
using std::vector;
using std::cin;
using std::endl;
using std::getline;
using std::fstream;
struct Games
{
 string name;
 string gender;
 string clasification;
 int year;
};
struct VectorGames
{
 vector<Games>VectorForGames;
 void InsertGame(string n, string g, string c, int y)
 {
    Games New = Games();
    New.name = n;
    New.gender = g;
    New.clasification = c;
    New.year = y;
    VectorForGames.push_back(New);
 }
};
int main()
{
 string name;
 string gender;
 string clasification;
 int year = 0;
 int option = 0;
 VectorGames V;
 fstream File("SavedGames.txt", fstream::in | fstream::out | fstream::app |     fstream::ate);
 do
 {
    cout << "1. Register a game " << endl
        << "2. Show the list of games registered" << endl
        << "3. Exit " << endl;
    cout << "Type in your option: ";
    cin >> option;
    cin.get();
    switch (option)
    {
    case 1:
    {
        cout << "Type in the name: ";
        getline(cin, name);
        cout << "Type in the gender: ";
        getline(cin, gender);
        cout << "Type in the clasification: ";
        getline(cin, gender);
        cout << "Type in the year: ";
        cin >> year;
        V.InsertGame(name, gender, clasification, year);
        if (File.is_open())
            File << "Name: " << name << "  Gender: " << gender
            << " Clasification: " << clasification << " Year: " << year << endl;
        break;
    }
    case 2:
    {
        string temporal;
        while (getline(File, temporal))
        {
            cout << temporal << endl;
        }
        break;
    }
    case 3: File.close();
        break;
    default: cout << "Try again" << endl;
    }
} while (option != 3);
return 0;

}

    cout << "Type in the gender: ";
    getline(cin, gender);
    cout << "Type in the clasification: ";
    getline(cin, gender);

问题不在于将输入的"分类"保存在文件中。问题是你把它读错了变量。