Last element of vector always disappears (C++)

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 590 Views - Last Post: 08 February 2012 - 06:48 AM Rate Topic: -----

Topic Sponsor:

#16 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 3756
  • View blog
  • Posts: 9,707
  • Joined: 16-October 07

Re: Last element of vector always disappears (C++)

Posted 08 February 2012 - 06:48 AM

OMG, globals! Don't use globals. Almost never use globals. There really no excuse to use them here.

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.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2