我一直用这段代码停留在同一个地方。最后决定在网上提问。任何帮助,将不胜感激。从C++中的文本文件读取/写入结构
我已经创建了一个结构体,我可以将数据添加到结构中,但仍不确定我是否遵循了正确的方法。当我尝试从文本文件读取数据时,主要问题在于。
我似乎得到一个错误说:
错误C2678:二进制“>>”:没有运营商发现,这需要左手 数类型的“的std :: ifstream的”(或有没有可接受的转化率)
结构体:
struct bankDetails //structure for bank details
{
int acc_number;
double acc_balance;
double deposit_amt;
double withdraw_amt;
double interest_rate;
//char acc_type;
};
struct CustDetails //structure for account details
{
string cust_name;
string cust_pass;
bankDetails bankAccounts[99];
};
这是我写从文件中读取的代码。
CustDetails loadDataFromFile()
{
CustDetails x;
ifstream dimensionsInfile;
dimensionsInfile.open ("storage.txt");
for (int i=0; i < 2; i++)
{ // write struct data from file
dimensionsInfile>>
&x.bankAccounts[i].acc_balance>>
&x.bankAccounts[i].acc_number>>
&x.cust_nam>>
&x.cust_pass>>
&x.bankAccounts[i].withdraw_amt>>
&x.bankAccounts[i].deposit_amt>>
&x.bankAccounts[i].interest_rate>>
cout<<"Data loaded"<<endl;
}
return x;
}
的代码写入到文件:主要功能
void details_save(int num,CustDetails x)
{
string filePath = "storage.txt";
ofstream dimensionsOutfile;
dimensionsOutfile.open ("storage.txt");
if (!dimensionsOutfile)
{
cout<<"Cannot load file"<<endl;
return ;
}
else
{
for (int i=0; i < num; i++)
{ // write struct data from file
dimensionsOutfile<<
&x.bankAccounts[i].acc_balance<<
&x.bankAccounts[i].acc_number<<
&x.cust_name<<
&x.cust_pass<<
&x.bankAccounts[i].withdraw_amt<<
&x.bankAccounts[i].deposit_amt<<
&x.bankAccounts[i].interest_rate<<
cout<<" Customer 1 stored"<<endl;
}
cout <<"All details have been successfully saved"<<endl;
dimensionsOutfile.close();
}
}
部分:
#include "stdafx.h"
#include <string>
#include <string.h>
#include <ctime>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
int main()
{
int maxNum;
CustDetails c;
c = loadDataFromFile(); //loads data from the file
{
//This part adds and changes values
}
details_save(maxNum, c); //saves data back to the file
return 0;
}
我在C++初学者任何帮助,将不胜感激。 干杯!
您将指针保存在文件中而不是实际数据中。 – drescherjm
直接的问题是您正在通过指针将参数传递给各个字段。删除'&':输入opwrators通过引用获取值。 ......最重要的是:你总是**需要在读取操作后检查**是否成功(如果你刚刚学习了最后一点,你刚刚做出了巨大的飞跃)。 –