Search code examples
c++fstreamofstream

When I write to my file it clears all the previous data in that file


I've been scanning through stackoverflow but I'm not finding any previous posts on my situation.

My program I want to write is just something to keep track of daily tips, hours worked, and number of days worked. So far it prints and creates a tips.txt file, but for some reason every time I run the program to input additional numbers it clears the previous entries . Still a lot of work that needs to be done, but I want to fix this problem first. Any ideas?

#include <fstream>
#include <iostream>
using namespace std;
int daysWorked(int); // Caculates the number of days worked
int hoursWorked(int); // Caculates hours worked
double profit(double); // Caculates the profit year to date

int main()
{
double tip;
int hours;
int month, day;
ofstream readFile;

cout << " Enter the month and then the day,  followed by hours worked, followed by money made" << endl;

if (!"tips.txt") // checks to see if tips.txt exists
{
    ofstream readFile("tips.txt"); // if tips.txt doesn't exists creates a .txt
}
else
    readFile.open("tips.txt" , std::ios::app && std::ios::in && std::ios::out); // if tips.txt exits just opens it? 

if (cin >> month >> day >> hours >> tip) // reads in the user input
{
    cout << endl;
    readFile << " Date :" <<  month << "/" <<  day << " " <<  "Hours:" << hours << " " << "Money made: " << tip << endl; // prints out the user input 
    cout << endl;
    readFile.close();
}

return 0;

}


Solution

  • Remove the following code:

    // As rpattiso stated, this does not test for the existence of a file
    //if (!"tips.txt") // checks to see if tips.txt exists
    //{
    //    ofstream readFile("tips.txt"); // if tips.txt doesn't exists creates a .txt
    //}
    //else
    

    This alone should be sufficient:

    // This will create the file if it doesn't exist and open existing files for appending (so you don't need to test if the file exists)
    ofstream readFile.open("tips.txt" , std::ios::app); // open for writing in append mode