Functions, however, are nice:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
// Globals BAD
void buyProduct(vector<string> &);
bool loadData(const char *, vector<string> &);
void showData(const vector<string> &);
int menu();
int main() {
vector<string> allLines;
if (!loadData("items.txt", allLines)) {
cout << "\nUnable to open file\n";
}
bool done = false;
while(!done) {
switch (menu()) {
case 1: buyProduct(allLines); break;
case 2: showData(allLines); break;
case 3: done = true; break;
default:
cout << "\n\nInvalid option! Try again.\n";
}
}
return 0;
}
bool loadData(const char *filename, vector<string> &allLines) {
ifstream myfile(filename);
if (myfile.is_open()) {
allLines.clear();
string line;
while (getline (myfile,line)) {
allLines.push_back(line);
}
myfile.close();
return true;
}
return false;
}
void showData(const vector<string> &d) {
cout << "Displaying data:\n\n";
for(vector<string>::const_iterator it=d.begin(); it!=d.end(); ++it) {
cout << *it << endl;
}
cout << "\nNumber of lines: " << d.size() << endl;
}
int menu() {
int option;
cout << "\n\nChoose an option (enter 1 - 3): \n"
<< "1. Buy product\n"
<< "2. Display products\n"
<< "3. Exit\n\n";
cin >> option;
return option;
}
void buyProduct(vector<string> &allLines) { /* your code here */ }
It looks like you're constantly parsing and unparseing your line from a string to three pieces of product data. Consider using an object for this:
struct Product {
string code, name;
int amount;
bool parse(const string &);
void writeLine(ostream &);
};
// ...
vector<Product> products;
Hope this helps.

New Topic/Question
Reply





MultiQuote


|