1

I'm having a problem, I want to save all ID numbers in the text file, but it only saves the last ID number that user input.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{

    string line;
    int idnum;
    ofstream IdData ("data.txt");

    cout<<" Enter your ID number: "<<endl;
    cin>>idnum;

    if(IdData.is_open())
    {
        IdData<< "ID number of voter is: ";
        IdData << idnum << endl;
        IdData.close();
    }
    else 
        cout<<" Unable to open file";


    ifstream Data ("data.txt");

    if(Data.is_open())
    {
        while (getline (Data, line))
        {
            cout<< line << endl;
        }

        Data.close();
    }
    else
        cout<<" Unable to open file";
}
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141

1 Answers1

0

You are asking the user for only 1 ID, and then you are overwriting the existing file with a new file that contains that 1 ID.

std::ofstream destroys the contents of an existing file unless you explicitly request it not to do so. So, for what you are attempting to do, to append a new ID to the end of the existing file, you need to include the app or ate flag when opening the std::ofstream (see C++ Filehandling: Difference between ios::app and ios::ate?), eg:

ofstream IdData ("data.txt", ios::app);

Or:

ofstream IdData ("data.txt", ios::ate);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770