开发者

Initializing nodes in a list from a .txt file

开发者 https://www.devze.com 2023-03-17 17:17 出处:网络
Currently have a custom Linked List class that works well. I implemented a function that can export all the contents of each Node to a .txt file when the program exits. I now want to import that same

Currently have a custom Linked List class that works well.

I implemented a function that can export all the contents of each Node to a .txt file when the program exits. I now want to import that same file to re-populate the list at the program start, and that's where I ran into some difficulty. (the >> and << operators are overloaded) and this entire linked-list class is specific to this program and not really meant to be re-usable.

my export function:

void List::exportData(){
    Node *currentPtr = Head;
    cout<<"Saving Data..."<<endl;
    ofstream fileOut("stock_transaction_history.txt");
    while (currentPtr != 0){
        fileOut<< currentPtr->symbol << " " <<currentPtr->shares<<endl;
        currentPtr = currentPtr->next; //iterates down the list
    }
}

Now I'm completely stuck on the import data feature. I also have a function addToBack((Node *newPtr) at my disposal if necessary.

void List::importData(){
    Node *currentPtr
    ifstream stockIn("stock_transaction_history.t开发者_开发问答xt"); 

    }
    stockIn >> currentPtr->symbol >>currentPtr ->shares;//(Node(tempSymbol, num));
    currentPtr = currentPtr->next;
    stockIn.close();

}

I'm thinking I might have to call addToBack via something along the lines of Node *tempPtr=new Node(); or just call the generic data portion of my node?

here is my node.h

class Node
{
private:
    friend class List;
    string symbol;
    int shares;
    Node *next;
public:
    Node() 
        : next(0)
    {
    }


Suggestions:

Maintain a pointer to the last node.

This will speed up appends and make life easier.

Create append method.

This will append a node to the end of the list. Useful for general insertions too.

Import method uses append method.

The import method creates a new node, initializes it with data from the file, then calls the append method.

Implement operator >>(istream&) for Node class.

Encapsulation I/O into one cental place. Leave knowledge about class innererds to the class, not to the List.

Remove friend declaration from Node

Replace with get/set methods and link_to() methods. This loosens the coupling between Node and List.


Very simply, you could read the file as I have described below.

void List::importData(const char *filePath)
{
    // open the file.
    std::ifstream file(filePath);

    // storage for the values read from the stream.
    std::string symbol;
    int shares;

    // here we read the symbol from the file stream, with "file >> symbol".  the
    // return value of that expression is the stream 'file', so we can chain 
    // that to reading the share count with "file >> symbol >> shares".  notice
    // that we use this in a conditional - this is because the stream will 
    // evaluate to 'true' if there is more data to read, or 'false' otherwise.
    while ((file >> symbol >> shares))
    {
        // create the new node
        addToBack(symbol, shares);
    }
}

A few potential improvements to your List/Node arrangement. What i've given below ignores the problems of copy assignment and copy construction. As it stands, it'll blow up if you do either of these things - its left as an exercise to fix. But ultimately, i'd recommend using an std::list<StockItem>, where StockItem contains just the symbol and share_count.

#include <fstream>
#include <memory>

// the node class used in the list.  note that I have not declared the list
// to be a friend of the node.  its needed as the data members are public.  if
// you dont want the data to be public (e.g. you want to enforce certain
// operations) make them private, and provide accessor functions.  in this case
// StockNode is a struct, making the data members public by default.
struct StockNode
{
    std::string mSymbol;
    int mShares;
    StockNode *mNext;

    // custom constructor, which populates the symbol and shares.
    StockNode(const std::string& symbol, int shares)
    : mSymbol(symbol), mShares(shares), mNext(0)
    {
    }
};

class StockList
{
    // we store the head AND the tail of the list.  storing the tail allows for
    // fast appends.
    StockNode *mHead;
    StockNode *mTail;

  public:
    // we override the default constructor to initialize the head/tail pointers
    // to 0 (null).
    StockList() : mHead(0), mTail(0)
    {
    }

    // destructor - since we are using raw pointers, we need to manage the 
    // freeing of the StockNodes ourselfs (again, if we used a 
    // std::list<StockNode> we could have avoided this.
    ~StockList()
    {
        clear();
    }

    void clear()
    {
        StockNode *node = mHead;

        // while we havent reached the end of the list.
        while (node)
        {
            // find the next element
            StockNode *temp = node->mNext;

            // free the memory for the current element.
            delete node;

            // set node to the next element in the list.
            node = temp;
        }

        // reset the pointers
        mHead = 0;
        mTail = 0;
    }

    // appends a node to the list.  i have called it push_back in line with the
    // standard library implementation std::list (which you would normally use
    // here, but it looks like this is homework).  notice that the parameter
    // is not a pointer, but a std::auto_ptr.  look up the documentation for it
    // to see exactly how it works.  its not *required* here, but i use it so 
    // the interface documents that we are taking ownership of the node.
    void push_back(std::auto_ptr<StockNode> stockNode)
    {
        // notice below the calls to "release", this stops the std::auto_ptr
        // managing the memory - so it doesn't free the memory when we still 
        // need it.

        if (mTail)
        {
            // the tail is set, write the new value.
            mTail->mNext = stockNode.release();
            mTail = mTail->mNext;
        }
        else
        {
            // no tail set means this is the first element, set the head and
            // the tail.
            mHead = stockNode.release();
            mTail = mHead;
        }
    }

    // ... implement other methods for looking up StockNodes, etc...

    void exportData(const std::string& filePath) const
    {
        std::ofstream file(filePath.c_str());

        for (StockNode *node = mHead; node; node = node->mNext)
        {
            // note that i have used '\n' instead of std::endl.  this is 
            // because std::endl prints the '\n' and flushes the stream
            // as we are writing to file, i figure it'll be a little quicker
            // if it doesnt flush to disk after every line.
            file << node->mSymbol << " " << node->mNext << '\n';
        }
    }

    void importData(const std::string& filePath)
    {
        std::ifstream file(filePath.c_str());

        std::string symbol;
        int shares;

        while ((file >> symbol >> shares))
        {
            push_back(std::auto_ptr<StockNode>(new StockNode(symbol, shares)));
        }
    }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号