[英]How to write multiple protocol buffers' messages into an a appendable compressed file?
[英]How does one store multiple instances of a variable of a structure in a while loop to an appendable .txt file
我正在編寫一個簡單的程序,將員工信息存儲到 .txt 文件中。 它應該無限地繼續寫入配置文件,直到選擇“n”來關閉文件。 問題是每次我輸入一個新的Emp。 以前的被覆蓋了,有人可以幫我看看我的疏忽嗎? 先感謝您。
#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;
}}
命名你的結構:
struct employee
{
string Names;
string Social;
double HourlyRate;
double HoursWorked;
};
然后在 main 中,制作這些員工結構的std::vector
。
( #include <vector>
在頂部)然后std::vector<employee> empvec
在 while 循環的頂部,創建一個新employee
employee temp;
在循環結束時, push_back()
包含所有數據的新employee
。 empvec.push_back(temp)
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.