0

従業員情報を .txt ファイルに保存する簡単なプログラムを作成しています。ファイルを閉じるために「n」が選択されるまで、プロファイルを無限に書き続けることになっています。問題は、新しい従業員を入力するたびに. 以前のものは上書きされます。誰かが私の見落としを確認するのを手伝ってくれますか? 前もって感謝します。

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

1 に答える 1

1

構造体に名前を付けます。

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

次に、主に、std::vectorこれらの従業員構造体を作成します。

#include <vector>上部)その後std::vector<employee> empvec

while ループの先頭で、新しいemployee employee temp;

ループの最後に、すべてのデータを含むpush_back()new . employee empvec.push_back(temp);

于 2011-05-02T11:08:24.747 に答える