-2

I am trying to make a simple program that can continously add data to a .txt document. Take a look at my code:

#include <iostream>
#include <fstream>

using namespace std;

int main () {
    ofstream playersW("players.txt");
    ifstream playersR("players.txt");

    int id;
    string name, info = "";
    float money;

    while (playersR >> id >> name >> money) {
        if (playersR.is_open()) {
            info += to_string(id) + " " + name + " " + to_string(money) + "\n";
        }
    }

    playersW << info;

    playersR.close();

    cout << "Enter player ID, Name and Money (or press 'CTRL+Z' + 'Enter' to quit):" << endl;

    while (cin >> id >> name >> money) {
        if (playersW.is_open()) {
            playersW << id << " " << name << " " << money << endl;
        }
    }

    playersW.close();
}

What I want is the program to first read the data that is stored in players.txt and then write it again and also add the new additional data to players.txt.

EDIT: With the code I have now, my program only writes in the file players.txt the new information that the user enters.

Guildencrantz
  • 1,875
  • 1
  • 16
  • 30
S. A.
  • 66
  • 11

1 Answers1

1

this is a simple program that can open the file players.txt in binary mode so it first reads the content and displays it then it asks the user to input new players until the user enters 0 or negative player id so the loop breaks and then it closes the file to save the new appended content:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{

    fstream players("players.txt");

    int id;
    string name, info = "";
    float money;

    while (players >> id >> name >> money)
        cout << name << "   " << id << "   "  << money << endl;

    players.clear();
    players.seekp(0, ios::end);

    cout << "Enter player ID, Name and Money (or press 'CTRL+Z' + 'Enter' to quit):" << endl;

    while(1)
    {
        cout << "id: "; 
        cin >> id;
        cout << endl;

        if(!cin || id <= 0)
            break;

        cout << "name: ";
        cin >> name;
        if(!cin)
            break;
        cout << endl;

        cout << "money: ";
        cin >> money;
        if(!cin)
            break;
        cout << endl;

        players << id << "   " << name << "   " << money << endl;
    }

    players.close();

    return 0;
}
Raindrop7
  • 3,889
  • 3
  • 16
  • 27