read/write 在 C++ 中从文本文件构造

read/write struct from text file in c++

一段时间以来,我一直被这段代码困在同一个地方。最后决定在线询问。任何帮助,将不胜感激。

我已经创建了一个结构,并且能够向该结构添加数据,但仍然不确定我是否遵循了正确的方法。主要问题在于当我尝试从文本文件中读取数据时。

我似乎收到一条错误消息:

error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::ifstream' (or there is no acceptable conversion)

结构:

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++ 的初学者,我们将不胜感激。 干杯!!

阅读该规范的 file formats. You may need to specify yours (on paper....), then you could use some EBNF 符号。

您当前的代码可能滥用了 operator >> and the operator <<. You don't want to write pointers on file (even if you technically could), because reading them again is meaningless (because of ASLR,并且因为不能保证地址从一个 运行 下一个保持不变,或者从一个可执行文件到您明天略有改进的程序)。

您可能想做一些二进制 IO(但我不建议这样做)。然后你会使用一些二进制输入函数,比如 std::istream::read to read a record (e.g. some POD struct)。但是你不能(有意义地)在复杂的 类 上执行二进制 IO,比如你的 CustDetails,包含非 POD 数据,比如 std::string-s.

其实,数据往往比读写它的软件更重要。所以拥有一些更灵活的数据格式是有意义的(例如,你希望能够在两年内让你的代码的 改进 版本读取一些由 您的代码的旧 版本)。

因此,通常最好使用某种文本格式(并且您需要对其进行定义和记录)。您可以选择一些现有的,例如 JSON, YAML, XML, S-expressions. You'll find many libraries to help you (e.g. jsoncpp for JSON etc etc...). Or you could also use your own parsing 技术。

你也可以考虑一些database, perhaps as simple as sqlite

另请参阅 serialization, application checkpointing, persistence, and portability

在 loadDataFromFile() 之前

cout<<"";

将“>>”替换为“;”。

我们不能在 cout 中使用 >> 运算符。

尽管有更好更简单的方法来完成您正在做的事情。 fstream.h 具有直接写入和读取 类 或结构的对象的功能。

语法如下:

<stream name>.read((char*)<object name>,sizeof(<struct/class name>));

所以你的loadDataFromFile可以简化为:

CustDetails loadDataFromFile ()
{
CustDetails x;
ifstream  dimensionsInfile; 
dimensionsInfile.open ("storage.txt");                                                              
     // write struct data from file  
     dimensionsInfile.read((char*) CustDetails, sizeof(x));   
     cout<<"Data loaded"<<endl;
     return x;
}

同样编写Write函数的定义。它将为您节省很多时间和麻烦。