I'm completely stuck on this assignment. I first wrote everything in int main() without any issue. It all worked lovely! Unfortunately our instructor wants it split up into multiple functions (less than 35 lines per function). I've split it up as you can see below but unfortunately my knowledge (and google hasn't been much help) of functions and passing/referencing through them is not that high. My program doesn't work at all now. All the 'Books' give errors so i'm not sure if I'm passing the struct or array improperly. Please help!
The original txt file reads like:
number of books
title
author
price
title
author
price
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
void setStruct() {
struct bookTable {
string title;
string author;
double price;
};
}
void setArray(int &arraySize, struct bookTable *Book[]) {
ifstream infile;
int bookCounter = 0;
infile.open("books2.txt");
if (!infile) {
cout << "Unable to open Books.txt" << endl;
}
infile >> arraySize;
infile.ignore(100, '\n');
bookTable *Book = new bookTable[arraySize];
infile.close();
}
void readFile(struct bookTable *Book[]) {
ifstream infile;
int bookCounter = 0;
infile.open("books2.txt");
for (int i = 0; getline(infile, Book[i].title); i++) {
getline(infile, Book[i].author, '\n');
infile >> Book[i].price;
infile.ignore(100, '\n');
bookCounter++;
}
infile.close();
}
void displayMenu(struct bookTable *Book[]) {
int menuChoice = 0, bookCounter = 0;
string findTitle;
do { cout << "\n===== Bookstore App =====" << endl;
cout << "1. Print Books" << endl;
cout << "2. Change Price" << endl;
cout << "3. Quit" << endl;
cout << "\nEnter Choice: ";
cin >> menuChoice;
if (menuChoice == 1) {
for (int i = 0; i < bookCounter; i++) {
cout << "===== BOOK =====" << endl;
cout << "Title: " << Book[i].title << endl;
cout << "Author: " << Book[i].author << endl;
cout << "Price: " << fixed << setprecision(2) << Book[i].price << endl; } }
else if (menuChoice == 2) { cin.ignore(100, '\n');
cout << "What is the title of the book? ";
getline(cin, findTitle, '\n');
for (int i = 0; i < bookCounter; i++) {
if (findTitle == Book[i].title) {
cout << "Enter New Price: " << endl;
cin >> Book[i].price;
}
else if (findTitle != Book[i].title) {
cout << "Unable to find Book" << endl;
}}}
else if (menuChoice < 1 || menuChoice > 3) {
cout << "Invalid Entry. Please enter 1, 2, or 3 from the options menu." << endl;
} } while (menuChoice != 3);
}
void writeFile(int arraySize, struct bookTable *Book[]) {
ofstream outfile;
int bookCounter = 0;
outfile.open("sale2.txt");
outfile << arraySize << endl;
for (int i = 0; i < bookCounter; i++) {
outfile << Book[i].title << endl;
outfile << Book[i].author << endl;
outfile << fixed << setprecision(2) << Book[i].price << endl;
}
outfile.close();
delete[] Book;
}
int main() {
setStruct();
setArray();
readFile();
displayMenu();
writeFile();
cout << "\nSale2.txt has been created." << endl;
return 0;
}