gpt4 book ai didi

c++ - 如何在 while 循环中将结构变量的多个实例存储到可附加的 .txt 文件中

转载 作者:行者123 更新时间:2023-11-28 08:20:57 25 4
gpt4 key购买 nike

我正在编写一个将员工信息存储到 .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) ;

关于c++ - 如何在 while 循环中将结构变量的多个实例存储到可附加的 .txt 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5856333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com