gpt4 book ai didi

c++将结构保存到文件中

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

我在将结构保存到文件的 C++ 函数中遇到问题。它似乎正确保存了所有内容,当我打开备份文件时,所有内容都已保存。但是当我再次运行程序时,加载文件由于某种原因进入无限循环,我不确定为什么会这样。欢迎任何意见。

#include <iostream> 
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>

using namespace std;

struct account
{
string acctNum;
string name;
float cBal;
float sBal;
};

int menu();
char subMenu();
int loadCustomers(account[]);
void saveCusomers(account[], int);
int newCustomer(account[], int);
int deleteCustomer(account[], int);
int findCustomer(account[], int);
void deposit(account[], int);
void withdrawl(account[], int);
void balance(account[], int);
void bankBalance(account[], int);

int main()
{
account acc[20];
int selection;
int numAcc = 0;

numAcc = loadCustomers(acc);

saveCusomers(acc, numAcc);

return 0;
}



int loadCustomers(account acc[])
{
ifstream inFile;
int numCustomers = 0, i = 0;

inFile.open("customer.dat");

if (!inFile)
{
cout << "No customer file found." << endl;
}

else
{
cout << "Customer file found..." << endl << endl;

while (!inFile.eof())
{
getline(inFile, acc[i].acctNum, '#');
getline(inFile, acc[i].name, '#');
inFile >> acc[i].cBal;
inFile.ignore();
inFile >> acc[i].sBal;

i++;
numCustomers++;
}

cout << "Number of customers found in file: " << numCustomers << endl;
}

inFile.close();

return numCustomers;
}

void saveCusomers(account acc[], int numCustomers)
{
ofstream outFile;

outFile.open("customer.dat");

for (int i = 0; i < numCustomers; i++)
{
outFile << acc[i].acctNum;
outFile << '#';
outFile << acc[i].name;
outFile << '#';
outFile << acc[i].cBal;
outFile << '#';
outFile << acc[i].sBal;
outFile << '#';
}

outFile.close();
}

我不确定我是在无限保存它还是为什么它会无限循环,任何评论都会有所帮助。

最佳答案

尝试替换

while (!inFile.eof())

 while(getline(inFile, acc[i].acctNum, '#'))

并删除getline(inFile, acc[i].acctNum, '#');作为你的第一句话

关于c++将结构保存到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27200194/

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