【发布时间】:2023-03-17 21:41:01
【问题描述】:
我已经被这段代码困在同一个地方一段时间了。最后决定在网上问一下。任何帮助,将不胜感激。
我已经创建了一个结构,并且可以向结构中添加数据,但仍然不确定我是否遵循了正确的方法。主要问题在于当我尝试从文本文件中读取数据时。
我似乎收到一条错误消息:
error C2678: binary '>>' : no operator found which take a left-hand '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++ 的初学者,任何帮助将不胜感激。 干杯!!
【问题讨论】:
-
您将指针保存在文件中,而不是实际数据。
-
当前的问题是您通过指针将参数传递给各个字段。删除
&:输入操作员通过引用获取值。 ...而且,最重要的是:您总是需要检查 *after 读取操作是否成功(如果您只了解最后一点,您就取得了巨大的飞跃前进)。
标签: c++ visual-c++ struct iostream ifstream