Search code examples
c++stringiostreamfstream

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


This a simple code for registering games in a file, but there are two problems.

First, the parameter or attribute "clasification" is not being saved in the file.

And second, when I read from the file, the content isn't shown.

Before commenting, you have to know that this is my first time working with files and I'm trying to learn on my own.

And I know this code lacks of modularity and I should declare a vector of pointers of objects, not to objects, or I should smart pointers, but I just wanted to show you the problem that I have with the file.

Any help is really appreciated

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

}


Solution

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

    The problem is not with saving the entered "classification" in a file. The problem is that you read it into the wrong variable.