• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C++ [fstream] Data Add, List and Search

Nous

New Coder
Hey guys,

A newbie here! šŸ‘‹

I have this problem, so I have to use c++ to add data to a txt file (item name, price) and after adding that I want to be able to save that txt file, be able to list all the data in the txt file and also search that txt file.

I am currently in the midst of programming this for one of my CS classes. Likewise, I have managed to create a void function to connect to the txt file and also a void function to add data to the txt file, somehow the data does not get stored. Every time I add a new item, it replaces the data in the txt file. I want to be able to create all add, list and search as void functions.

I am quite new to C++ and I have been trying my best to learn about fstream, ifstream and ofstream. If anyone can guide me in this I would really appreciate it.

Thanks!
 

Nous

New Coder
Here is the code I made for adding to the database, šŸ˜¬

C++:
void addDb() {
    string itemName;
    float itemPrice;
    int itemStock;

    ofstream dbfile;
     dbfile.open("database.txt");
     cout << "[Add New Furniture]" << endl;
     cout << "Please enter furniture name: " ;
     cin >> itemName;
     cout << "Please enter furniture unit price: " ;
     cin >> itemPrice;
     cout << "Please enter current stock in hand:" ;
     cin >> itemStock;
     dbfile << itemName << " " << itemPrice << " " << itemStock << "\n";
     dbfile.close();
     cout << "\n" << endl;
     cout << "[Added Successfully]" << endl;
     backtoMain();
}
 

Top