简体   繁体   中英

How does one store multiple instances of a variable of a structure in a while loop to an appendable .txt file

I am writing a simple program that stores employee info into a.txt file. It is supposed to continue writing profiles infinitely until 'n' is chosen to close file. The problem is that every time i enter in a new Emp. the previous gets overwritten, can someone help me see my oversight? Thank You in advance.

#include <iostream>
#include <fstream>
#include <cstdlib>   // needed for exit()  
#include <string>
#include <iomanip>  // needed for formatting

using namespace std;

struct
    {
        string Names;
        string Social;
        double HourlyRate;
        double HoursWorked;
    } employee_info;

int main()
{
    char contn = 'y';
    char exitf = 'n';
  string filename = "employee_info.txt";  // initialize the filename up front
  ofstream outFile;

  outFile.open(filename.c_str());
  fstream file1;
  if (outFile.fail())
  {
    cout << "The file was not successfully opened" << endl;
    exit(1);
  }

  {
      string employee;
    while (contn == 'y')
    {

    cout << "Please enter Employee Name \n";
    getline (cin,employee_info.Names);
    cout << "Please enter Employee Social Security Number \n";
    getline (cin,employee_info.Social);
    cout << "Please enter Employee's Hourly Rate \n";
    cin >> employee_info.HourlyRate;
    cout << "Please enter Hours Worked \n";
    cin >> employee_info.HoursWorked;
    cout << " Enter y if you would like to enter another employee. \nEnter n to write to file. : \n ";

    cin >> contn;
    cin.ignore();

  // set the output file stream formats
  outFile << setiosflags(ios::fixed)
        << setiosflags(ios::showpoint)
        << setprecision(2);

  // send data to the file
  }

  outFile << employee_info.Names <<endl<< employee_info.Social <<endl<< employee_info.HourlyRate <<endl<< employee_info.HoursWorked << endl;
file1.open("employee_info.txt",ios::app);
  }
while (exitf == 'n')
{
  outFile.close();
  cout << "The file " << filename 
       << " has been successfully written." << endl;

  return 0;
}}    

Name your struct:

struct employee
{
    string Names;
    string Social;
    double HourlyRate;
    double HoursWorked;
};

Then in main, make a std::vector of these employee structs.

( #include <vector> at the top) then std::vector<employee> empvec

At the top of the while loop, create a new employee employee temp;

At the end of the loop, push_back() your new employee with all of the data. empvec.push_back(temp) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM