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

时间:2016-04-09 01:59:16

标签: c++ string iostream fstream

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

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

其次,当我从文件中读取内容时,内容未显示。

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

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

非常感谢任何帮助

#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;

}

1 个答案:

答案 0 :(得分:0)

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

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