Advertisement Jump to content
Sign in to follow this  
Manhattanisgr8

C++ Need help with fstream

This topic is 1733 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I need help with fstream and linked lists. Basically I am creating a basic inventory program for a school project where I have to write a manual for it. What I am trying to do is store products in a linked list. When the user quits, it writes stores the data into a txt file. When the user opens it again, I want it to read from the text file to re-populate the list. The problem I am having is reading a line with spaces. I can get it to read once, but when it goes to the next list, it doesn't copy all the information from the second product. Below is all the code I have so far and commented out what I have tried. The problem lays in LinkedProductInventory.cpp in the constructor.

LinkedProductInventory.h

[spoiler]

#include <cstddef>

#include "Product.h"



using namespace std;



class LinkedProductInventory

{

private:

    struct ListNode

    {

        Product product;

        ListNode *next;

    };



    void sort();



    ListNode *head;

    int count;



public:

    LinkedProductInventory();

    //~LinkedProductInventory();



    void appendNode(Product);

    void insertNode(Product);

    void deleteNode(Product);

    void displayList();

    void writeToFile();

};

,[/spoiler]

LinkedProductInventory.cpp

[spoiler]


#include <iostream>

#include <fstream>

#include <string>

#include "LinkedProductInventory.h"



using namespace std;



LinkedProductInventory::LinkedProductInventory()

{

    head = NULL;

    count = 0;



    ifstream inFile;

    inFile.open("inventory.txt");



    if (inFile)

    {

        Product product;

        string productName, locator;

        int quantity;

        double price;



        //while ((inFile.peek() != '\n') && (getline(inFile, productName)))

        //while (getline(inFile, productName))

        while (inFile.getline(productName,productName.length))

        {

            //getline(inFile, productName);

            inFile >> locator;

            inFile >> quantity;

            inFile >> price;



            product.setProductName(productName);

            product.setLocator(locator);

            product.setQuantity(quantity);

            product.setPrice(price);

            inFile.clear();



            appendNode(product);

        }

    }

    else

        inFile.close();

}



void LinkedProductInventory::appendNode(Product product)

{

    ListNode *newNode; // To point to the new node

    // Create a new node and store data in it

    newNode = new ListNode;

    newNode->product = product;

    newNode->next = NULL;



    //If empty, make head point to new node

    if (head == NULL)

    {

        head = newNode;

    }

    else

    {

        ListNode *p = head; // To move through the list



        //traverse list to find last node

        while (p->next != NULL)

            p = p->next;



        // now p points to last node

        // make last node point to newNode

        p->next = newNode;

    }



    count++;

//    sort();

}



void LinkedProductInventory::displayList()

{

    ListNode *p;



    // start at head of the list

    p = head;



    cout << "\nLocation    Quantity    Price            Name" << endl;

    cout << "--------------------------------------------------------------------------" << endl;



    // while p points to something, continue

    while (p)

    {

        //Display the value in the current node

        cout << p->product.getLocator() << "\t";

        cout << p->product.getQuantity() << "\t\t";

        cout << p->product.getPrice() << "\t\t";

        cout << p->product.getProductName() << endl;



        //Move to the next node

        p = p->next;

    }



    cout << endl;

}



//LinkedProductInventory::~LinkedProductInventory()

//{

//    ListNode *p; // traversal pointer

//    ListNode *n; // saves the next node

//    p = head;

//

//    while (p)

//    {

//        n = p->next; //save the next

//        delete p; // delete current

//        p = n;

//    }

//}



void LinkedProductInventory::deleteNode(Product product)

{

    ListNode *p = head; // to traverse list

    ListNode *n = p; // trailing node pointer



    // skip nodes not equal to product, stop at last

    while (p && p->product.getProductName() != product.getProductName() && p->product.getLocator() != product.getLocator())

    {

        n = p;

        p = p->next;

    }



    //p not null: product was found, set links + delete

    if (p)

    {

        if (p == head)

        {

            head = p->next;

            delete p;

        }

        else

        {

            n->next = p->next;

            delete p;

        }

    }



    count--;

}



void LinkedProductInventory::writeToFile()

{

    ofstream outFile;



    outFile.open("inventory.txt");



    ListNode *p = head;



    while (p)

    {

        outFile << p->product.getProductName() << endl;

        outFile << p->product.getLocator() << endl;

        outFile << p->product.getQuantity() << endl;

        outFile << p->product.getPrice() << endl;



        p = p->next;

    }



    outFile.close();

}



void LinkedProductInventory::sort()

{

    ListNode *p = head; //used to traverse

    ListNode *temp;



    for (int x = 0; x < count; x++)

    {

        while (p)

        {

            if (p->product.getProductName() > p->next->product.getProductName())

            {

                temp = p->next;

                p->next = p;

                p = temp;

            }

            else

                continue;

        }

    }

}

[/spoiler]

Product.h

[spoiler]


// File Name: Product.h

//

// Author: Travis Alt

// Date: 3/31/2014

// Assignment Number: 5

// CS 2308.256 Spring 2014

// Instructor: Jill Seaman

//

// Header file for Product.cpp



#include <string>



using namespace std;



class Product

{

private:

    string productName; // name of the product

    string locator; // location of the product

    int quantity; // number of products

    double price; // price of the products



public:

    Product();

    Product(string, int, double, string);



    string getProductName();

    string getLocator();

    int getQuantity();

    double getPrice();



    void setProductName(string);

    void setLocator(string);

    void setQuantity(int);

    void setPrice(double);



    bool operator<(Product);

    bool operator>(Product);

    bool operator==(Product);

};

[/spoiler]

Product.cpp

[spoiler]


// File Name: Product.cpp

//

// Author: Travis Alt

// Date: 3/31/2014

// Assignment Number: 5

// CS 2308.256 Spring 2014

// Instructor: Jill Seaman

//

// A representation of a Product object that stores

// the product name, quantity, price, and location



#include "Product.h"



using namespace std;



//***********************************************************

// Product: Constructor of Product that takes no arguments

//

// returns nothing

//***********************************************************

Product::Product()

{

    productName = " ";

    locator = " ";

    quantity = 0;

    price = 0.00;

}



//***********************************************************

// Product: Constructor of Product that sets each member variable

//

// locator: location of the product

// quantity: the number of products

// price: the price of the products

// productName: name of the product

// returns nothing

//***********************************************************

Product::Product(string locator, int quantity, double price, string productName)

{

    this->productName = productName;

    this->locator = locator;

    this->quantity = quantity;

    this->price = price;

}



//***********************************************************

// getProductName: gets the name of the product stored in the

// member variable

//

// returns member variable productName

//***********************************************************

string Product::getProductName()

{

    return productName;

}



//***********************************************************

// getLocator: gets the location of the product stored in the

// member variable

//

// returns member variable locator

//***********************************************************

string Product::getLocator()

{

    return locator;

}



//***********************************************************

// getQuantity: gets the number of the products stored in the

// member variable

//

// returns member variable quantity

//***********************************************************

int Product::getQuantity()

{

    return quantity;

}



//***********************************************************

// getPrice: gets the price of the product stored in the

// member variable

//

// returns member variable price

//***********************************************************

double Product::getPrice()

{

    return price;

}



//***********************************************************

// setProductName: sets the name of the product stored in the

// member variable

//

// returns void

//***********************************************************

void Product::setProductName(string productName)

{

    this->productName = productName;

}



//***********************************************************

// setLocator: sets the location of the product stored in the

// member variable

//

// returns void

//***********************************************************

void Product::setLocator(string locator)

{

    this->locator = locator;

}



//***********************************************************

// setQuantity: sets the number of products stored in the

// member variable

//

// returns void

//***********************************************************

void Product::setQuantity(int quantity)

{

    this->quantity = quantity;

}



//***********************************************************

// setPrice: sets the price of the product stored in the

// member variable

//

// returns void

//***********************************************************

void Product::setPrice(double price)

{

    this->price = price;

}



//***********************************************************

// operator<: An overloaded operator that checks if the product

// name is less than product on the right

//

// right: the product on the right side of the argument

// returns true if the product on the left is less than the product

// on the right

//***********************************************************

bool Product::operator<(Product right)

{

    if (productName < right.getProductName())

    {

        return true;

    }

    else

        return false;

}



//***********************************************************

// operator>: An overloaded operator that checks if the product

// name is greater than product on the right

//

// right: the product on the right side of the argument

// returns true if the product on the left is greater than the product

// on the right

//***********************************************************

bool Product::operator>(Product right)

{

    if (productName > right.getProductName())

    {

        return true;

    }

    else

    {

        return false;

    }

}



//***********************************************************

// operator==: An overloaded operator that checks if the product

// name is equal to than product on the right

//

// right: the product on the right side of the argument

// returns true if the product on the left is equal to than the product

// on the right

//***********************************************************

bool Product::operator==(Product right)

{

    if (productName == right.getProductName())

    {

        return true;

    }

    else

    {

        return false;

    }

}

[/spoiler]

ProductDriver.cpp

[spoiler]


#include <iostream>

#include <string>

#include "LinkedProductInventory.h"



using namespace std;



void readFromFile();

Product *addProduct();

Product *removeProduct();

Product *adjustQuantity();

string displayProduct();



int main()

{

    const int ADD_NEW = 1,

        REMOVE = 2,

        ADJUST_QUANTITY = 3,

        DISPLAY_INFO = 4,

        DISPLAY_INVENTORY = 5,

        QUIT = 6;

    int userSelection;

    LinkedProductInventory pi;



    do

    {

        cout << "Manage Inventory Menu" << endl;

        cout << "1. Add product" << endl;

        cout << "2. Remove product" << endl;

        cout << "3. Adjust Quantity of A Product" << endl;

        cout << "4. Display A Product" << endl;

        cout << "5. Display Inventory" << endl;

        cout << "6. Quit The Program" << endl;



        cout << "\nEnter your choice: ";

        cin >> userSelection;



        string productName, locator;

        int quantity;

        double price;

        Product product;



        switch (userSelection)

        {

        case 1:

            



            cout << endl;

            cout << "Please enter the product's name: ";

            cin.ignore(100, '\n');

            getline(cin, productName);

            product.setProductName(productName);



            cout << "Please enter the product's location: ";

            cin >> locator;

            product.setLocator(locator);



            cout << "Please enter the quantity of the product (DO NOT INCLUDE SPACES): ";

            cin >> quantity;

            product.setQuantity(quantity);



            cout << "Please enter the price of the product: ";

            cin >> price;

            product.setPrice(price);



            pi.appendNode(product);



            cout << endl;

            break;



        case 2: pi.deleteNode(*removeProduct());

            cout << endl;

            break;



        case 3: adjustQuantity();

            cout << endl;

            break;



        case 4: displayProduct();

            cout << endl;

            break;



        case 5: pi.displayList();

            cout << endl;

            break;



        case 6: pi.writeToFile();

            break;

        }



    } while (userSelection != QUIT);



    

}



Product *addProduct()

{

    string productName;

    string locator;

    int quantity;

    double price;



    cout << endl;

    cout << "Please enter the product's name: ";

    cin.ignore(100, '\n');

    getline(cin, productName);

    //product.setProductName(productName);



    cout << "Please enter the product's location: ";

    cin >> locator;

    //cin.ignore(100, '\n');

    //getline(cin, locator);

    //product.setLocator(locator);



    cout << "Please enter the quantity of the product (DO NOT INCLUDE SPACES): ";

    cin >> quantity;

    //product.setQuantity(quantity);



    cout << "Please enter the price of the product: ";

    cin >> price;

    //product.setPrice(price);



    Product product(locator, quantity, price, productName);

    Product *p = &product;

    return p;



}



Product *removeProduct()

{

    string productName, locator;



    cout << endl;

    cout << "Please enter the product's name to remove: ";

    cin.ignore(100, '\n');

    getline(cin, productName);

    cout << "Please enter the location of the product: ";

    cin.ignore(100, '\n');

    getline(cin, locator);

    

    Product product(locator, 0, 0.0, productName);

    Product *p = &product;



    return p;

}



// may have to redo this

Product *adjustQuantity()

{

    Product product;

    string productName, locator;

    int newQuantity;



    cout << endl;

    cout << "Enter the name of the product: ";

    cin.ignore(100, '\n');

    getline(cin, productName);

    cout << "Enter the location of the product: ";

    cin.ignore(100, '\n');

    getline(cin, locator);



    cout << "Enter the new quantity of the product: ";

    cin >> newQuantity;



    product.setProductName(productName);

    product.setLocator(locator);

    product.setQuantity(newQuantity);



    Product *p = &product;

    return p;

}



string displayProduct()

{

    Product product;

    string productName;



    cout << endl;

    cout << "Enter the product name: ";

    cin.ignore(100, '\n');

    getline(cin, productName);



    return productName;

}



[/spoiler]

 

EDIT: Here is what the txt file looks like:

Samsung
Livingroom
2
12.99
Test this
Livingroom
4
56.88

Edited by Manhattanisgr8

Share this post


Link to post
Share on other sites
Advertisement
Instead of posting all your code, you could have just written a 10-line program that tries to read from the format you describe, and posted that.

Handling input is surprisingly hard to get right. For a text format like the one you are dealing with, you should read whole lines using getline, and not use operator >>. In your code you are mixing both, and that has some problems. Specifically, when you read something from a line with operator >>, you are not consuming the new-line character at the end of the line. The next getline call will then see an empty line.

So just use getline consistently to read everything. For strings it's very straight forward. For other types, getline will give you a string and then you can use that string to build a std::istringstream from which you read the value you want, using operator >>.

Share this post


Link to post
Share on other sites


Specifically, when you read something from a line with operator >>, you are not consuming the new-line character at the end of the line. The next getline call will then see an empty line.

 

Thanks Alvaro, I fixed the problem I was having by consuming the newline character with cin.ignore() before it looped back around to the getline() statement.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!