C++ Out Of Range When using Vector - c++

So I have created a Binary Search Tree (BST) by placing nodes into a vector. These nodes store 3 values, a user input int ID, a user input int age, and a user string input name.
When inserting these nodes into the vector, they are stored going in ascending order.
Currently I'm working with two nodes.
104 10 Bob
102 11 Steve
When pushing back the first node, there are no problems; however, when attempting to push back the second node, I am getting an out_of_bounds error thrown by the vector class.
I believe something is wrong with my insert function when attempting to switch the positions of these two nodes, however I can't tell exactly where the issue lies.
#include "BinaryTree.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int index;
struct Node
{
int ID;
int age;
string name;
Node()
{
}
Node(int id, int Age, string nm)
{
this->ID = id;
this->age = Age;
this->name = nm;
}
};
vector<Node> binaryTree;
BST::BST()
{
}
void BST::start()
{
int choice;
cout << "What would you like to do?" << endl;
cout << "1. Add a node to the tree" << endl;
cout << "2. Delete a node from the tree" << endl;
cout << "3. Find a node in the tree" << endl;
cout << "4. Report the contents of the tree" << endl;
cout << "5. Exit program" << endl;
cin >> choice;
if (choice == 1)
{
insert();
}
if (choice == 3)
{
find();
}
if (choice == 4)
{
report();
}
}
void BST::insert()
{
int ID;
int AGE;
string NAME;
cout << "Please enter the ID number, age and name" << endl;
cin >> ID >> AGE >> NAME;
Node *tree = new Node(ID, AGE, NAME);
if (index == 0)
{
binaryTree.push_back(*tree);
index++;
}
if (index > 0)
{
if ((binaryTree.at(index - 1).ID) < ID)
{
binaryTree.push_back(*tree);
index++;
}
}
if (index > 0)
{
if ((binaryTree.at(index - 1).ID) > ID)
{
Node *temp = new Node();
*temp = binaryTree.at(index - 1);
binaryTree.at(index - 1) = *tree;
binaryTree.at(index) = *temp;
index++;
}
}
cout << "Added! Size: " << binaryTree.size() << endl;
cout << " " << endl;
start();
Would appreciate the help! Thanks!

Your vector doesn't resizes when you do this: binaryTree.at(index) = *tree;
Do push_back() then try sort
binaryTree.push_back(*tree;)
std::sort(binaryTree.begin(),binaryTree.end(),[](const Node& n1, const Node& n2){//do your comparations});
Or simply use std::set
If you want to work with std::vector without crashing, then your insert() have to look like this:
void BST::insert()
{
int ID;
int AGE;
string NAME;
cout << "Please enter the ID number, age and name" << endl;
cin >> ID >> AGE >> NAME;
//Node *tree = new Node(ID, AGE, NAME); // Don't use new here, there is no need in this
Node tree(ID, AGE, NAME);
binaryTree.push_back(tree);
std::sort(binaryTree.begin(), binaryTree.end(), [](const Node& n1, const Node& n2)
{
//compare your nodes here
return (n1.ID > n2.ID);
});
cout << "Added! Size: " << binaryTree.size() << endl;
cout << " " << endl;
start();
}
But this won't be a binary tree. You need other data structure to create binary tree, std::vector can't be binary tree.
There is a ready solution for you, look at std::set, It inserts elements like you need, you will need to add your custom compare function to std::set and everything will be fine.
Here is std::set example for you:
class Node
{
public:
Node(int id):ID(id){}
int ID;
};
class NodeComparator
{
public:
bool operator()(const Node& n1,const Node& n2)
{
return n1.ID < n2.ID;
}
};
int main()
{
std::set<Node, NodeComparator> set1;
set1.insert(10);
set1.insert(8);
set1.insert(14);
set1.insert(2);
return 0;
}
Here is what you need, std::set sorted ascending:

std::vector has methods other than push_back for inserting elements. Specifically, insert takes a position, where the new element is to be inserted. emplace is even better, as you don't even have to create an element to copy into the vector, you just pass the constructor arguments.
You can find the appropriate place to insert at with std::lower_bound.
#include <algorithm>
void BST::insert()
{
int ID;
int AGE;
std::string NAME;
std::cout << "Please enter the ID number, age and name" << std::endl;
std::cin >> ID >> AGE >> NAME;
auto pos = std::lower_bound(binaryTree.begin(), binaryTree.end(),
[](const Node& n1, const Node& n2) { return (n1.ID > n2.ID); });
binaryTree.emplace(pos, ID, AGE, NAME);
std::cout << "Added! Size: " << binaryTree.size() << endl;
std::cout << " " << std::endl;
// start(); // dubious, see below
}
As an aside, your insert method knowing about start is leaking assumptions that you may later want to change. It would be much better to contain that all within start, like:
void BST::start()
{
std::cout << "What would you like to do?" << std::endl;
std::cout << "1. Add a node to the tree" << std::endl;
std::cout << "2. Delete a node from the tree" << std::endl;
std::cout << "3. Find a node in the tree" << std::endl;
std::cout << "4. Report the contents of the tree" << std::endl;
std::cout << "5. Exit program" << std::endl;
for(int choice; (std::cin >> choice) && (choice != 5);)
{
switch (choice)
{
case 1: insert(); break;
case 3: find(); break;
case 4: report(); break;
}
}
}

Related

How to connect sections of an array or organize an array the same as another?

I am not sure how to connect a part of an array or if it is even possible.
My code is as follows:
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
string name;
string date[3];
double height[3];
double enter;
cout << "Enter name of a pole vaulter: ";
cin >> name;
cout << "Enter date of first vault: ";
cin >> date[0];
cout << "Enter height of first vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[0] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
cout << "Enter date of second vault: ";
cin >> date[1];
cout << "Enter height of second vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[1] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
cout << "Enter date of third vault: ";
cin >> date[2];
cout << "Enter height of third vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[2] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
int len = sizeof(height) / sizeof(height[0]);
sort(height, height + len, greater<int>());
cout << "Stats for " << name << ":" << endl;
for (int i = 0; i < len; i++) {
cout << height[i] << " ";
}
cout << height[0];
}
I am trying to enter dates and a double value, and then organize the double values in descending order and keep the dates with the corresponding value. I am not sure if this is possible, any alternative way of completing this would be helpful.
Thank you
Group of data, data sorting, multiple data points that should be aligned/connected to their respective other data points. I think the best solution here would be the use of a struct or class with vectors:
Let's say you want a variable that contains both your date and number. We can construct a class or structure for that:
#include <iostream>
using namespace std;
struct str1
{
string date;
double number;
};
class cls1
{
public:
string date;
double number;
};
int main()
{
str1 ob1;
cls1 ob2;
ob1.date = "somedate";
ob1.number = 12345;
cin >> ob1.date;
cout << ob1.date << " " << ob1.number << endl;
ob2.date = "somedate2";
ob2.number = 54321;
cin >> ob2.number;
cout << ob2.date << " " << ob2.number << endl;
return 0;
}
Having a class or struct enables you to use objects (variables made from those structs or classes). Every object created has their own place in memory for storing both date and number. You can use, find, search any of these variables and have access to both values this way.
Grouping them up so there's a list of them can be done in vectors.
Vectors are like better arrays. They not only have a dynamical size (meaning its size can change and doesnt stay static like in arrays), but they also have quite a bit ready made functions for you to use:
bool sortingFunction(int &a, int &b)
{
if (a > b) return true;
else return false;
}
int main2()
{
vector<int> numbers;
//to add
numbers.emplace_back(5); //5 is the number to add
//to remove
numbers.erase(numbers.begin() + 2); //2 is the index of the variable to delete
//to sort
sort(numbers.begin(), numbers.end(), sortingFunction);
return 0;
}
Vectors need the #include <vector> header.
Sort is a function that sorts. Needs #include <algorithm> header.
Sort function is neat because you can define the logic behind how you want to sort the vector or array with a seperate function that returns either true or false.
For your example you could do something like this in the end:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct myType
{
string date;
double number;
};
bool sortByDate(myType &a, myType &b)
{
if (a.date > b.date) return true;
else return false;
}
bool sortByNumber(myType &a, myType &b)
{
if (a.number > b.number) return true;
else return false;
}
int main()
{
vector<myType> variables;
int num;
cout << "how many do you want to add" << endl;
cin >> num;
for(int i = 0; i < num; i++)
{
myType tmp;
cout << "Enter date of var" << i+1 << ": ";
cin >> tmp.date;
cout << "Enter number of var" << i+1 << ": ";
cin >> tmp.number;
variables.emplace_back(tmp);
}
//after that you can use the vector as you want...
//sort
sort(variables.begin(), variables.end(), sortByDate);
sort(variables.begin(), variables.end(), sortByNumber);
//delete
variables.erase(variables.begin()+5);
//or clear the entire thing
variables.clear();
//Either way each item in the vector consists of both number and date thus even
//if you sort the vector the values are still connected at the same position
return 0;
}

How to store an instance of class in a vector?

I have made a class for a student with course and grade, the program keeps asking for a new student until the name given is stop. To store these instances I want to use a vector, but I didn't find any other way to store them than creating an array for the instances first and then pushing them back into the vector.
Is it possible to have room for one instance and delete the values stored in Student student after use so it can be reused?
int i=0;
Student student[20];
vector<Student> students;
cout << "Name?" << endl;
getline(cin,student[i].name);
while((student[i].name) != "stop")
{
student[i].addcoursegrade();
students.push_back(student[i]);
i++;
cout << "Name?" << endl;
getline(cin,student[i].name);
if((student[i].name) == "stop")
break;
};
I also use vectors inside the class to store the values for course and grade, since they are also supposed to be growing. The code for the class is here:
class Student {
public:
string name;
void print() {
cout << name ;
for (int i = 0; i < course.size(); i++)
cout << " - " << course[i] << " - " << grade[i];
cout<<endl;
}
void addcoursegrade() {
string coursee;
string gradee;
cout << "Course?" << endl;
getline(cin, coursee);
course.push_back(coursee);
while (coursee != "stop") {
cout << "Grade?" << endl;
getline(cin, gradee);
grade.push_back(gradee);
cout << "Course?" << endl;
getline(cin, coursee);
if (coursee != "stop")
course.push_back(coursee);
else if(coursee == "stop")
break;
}
};
private:
vector<string> course;
vector<string> grade;
};
Instead of creating an array then pushing back, simply keep one instance around and reassign it:
Student student;
vector<Student> students;
cout << "Name?" << endl;
getline(cin,student.name);
while((student.name) != "stop")
{
student.addcoursegrade();
// this line copies the student in the vector
students.push_back(student);
// then, reassign the temp student to default values
student = {};
cout << "Name?" << endl;
getline(cin,student.name);
if((student.name) == "stop")
break;
};
A few things bothered me:
The way your loops were structured, duplicating the getline. I prefer a while(true) array with a break when the terminating input appears.
No need for a C-style array. std::vector is the way!
separate arrays for course and grade. Instead, I prefer a single record that stores both the course and the grade
indices in your loops that are only used to access the items within the collection. (Just use a range-based for loop)
Don't make a Student object until you need to. Use local variables for string inputs.
As with anything in C++, lots more could be done do to improve it: things like add constructors for your objects, initialize with modern syntax, embrace move semantics, etc. But I'm just making minimal changes.
I'd tackle it like this:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
struct CourseGrade {
string course;
string grade;
};
class Student {
public:
string name;
void print() {
cout << name;
for (auto& courseGrade : courseGrades) {
cout << " - " << courseGrade.course << " - " << courseGrade.grade;
}
cout << endl;
}
void addcoursegrades() {
while (true) {
cout << "Course?" << endl;
string course;
getline(cin, course);
if (course == "stop") break;
cout << "Grade?" << endl;
string grade;
getline(cin, grade);
CourseGrade courseGrade;
courseGrade.course = course;
courseGrade.grade = grade;
courseGrades.push_back(courseGrade);
}
}
private:
vector<CourseGrade> courseGrades;
};
int main() {
vector<Student> students;
while (true) {
cout << "Name?" << endl;
std::string name;
getline(cin, name);
if (name == "stop") break;
Student student;
student.name = name;
student.addcoursegrades();
students.push_back(student);
};
for (auto& student : students) {
student.print();
}
}

MultiMap not Printing List

I am having 2 issues with my code.
The 1st issue is that my multimap is not printing, and I don't know why.
The 2nd issue is that I don't know how to create a function to search and find a specific item in my multimap.
You can change as much of the code as you want, but I need to keep the class or change it to a struct.
#include<iostream>
#include<string>
#include<iterator>
#include<map>
#include<algorithm>
#include<iomanip>
using namespace std;
class SongNode {
public:
string title;
string artist;
float rating;
};
//Constants
#define INFINITE_LOOP 1
#define LEFT_JUSTIFIED 30
//Prototypes
void sortByArtist(multimap<string, SongNode>& newSongNode);
void sortByRating(multimap<string, SongNode>& newSongNode);
//FUNCTION : void sortByArtist
//PARAMETER : multimap<string, SongNode>&newSongNode
//RETURN : void
//DESCRIPTION : This function will sort the multimap by the artist of the song
void sortByArtist(multimap<string, SongNode>&newSongNode) {
multimap<string, SongNode>temp;
for (auto i = newSongNode.begin(); i != newSongNode.end(); i++)
temp.insert(pair<string, SongNode>(i->second.artist, i->second));
newSongNode.clear();
for (auto i = temp.begin(); i != temp.end(); i++)
newSongNode.insert(pair<string, SongNode>(i->second.artist, i->second));
temp.clear();
}
//FUNCTION : void sortByRating
//PARAMETER : (multimap<string, SongNode>& newSongNode
//RETURN : void
//DESCRIPTION : This function will sort the multimap by the rating.
void sortByRating(multimap<string, SongNode>& newSongNode) {
multimap<float, SongNode, greater<int>> temp;
for (auto i = newSongNode.begin(); i != newSongNode.end(); i++)
temp.insert(pair<int, SongNode>(i->second.rating, i->second));
newSongNode.clear();
for (auto i = temp.begin(); i != temp.end(); i++)
newSongNode.insert(pair<string, SongNode>(" ", i->second));
temp.clear();
}
int main() {
multimap<string, SongNode> songList;
multimap<string, SongNode>::iterator itr;
string title;
string artist;
int rating;
SongNode* newSongNode = new SongNode;
cout << "Please enter a title artist and rating\n";
while (INFINITE_LOOP) {
cout << "Title: ";
cin >> title;
if (title == ".") {
break;
}
cout << "Artist: ";
cin >> artist;
cout << "Rating: ";
cin >> rating;
//Error check for rating
while (INFINITE_LOOP) {
if (rating < 1) {
cout << "The rating you have entered is less then 1\n";
cout << "Rating: ";
cin >> rating;
break;
}
else if (rating > 5) {
cout << "The rating you have to enterd is greater then 5\n";
cout << "Rating: ";
cin >> rating;
break;
}
else
break;
}
SongNode* newNode = new SongNode;
newNode->title = title;
newNode->artist = artist;
newNode->rating = rating;
songList.insert(pair<string, SongNode>(title, *newSongNode));
}
//display the two lists here.
cout << "Artist Sorted List\n";
sortByArtist(songList);
for (itr = songList.begin(); itr != songList.end(); ++itr) {
cout << "Title" << left << setw(LEFT_JUSTIFIED) << itr->second.title;
cout << "Artist" << left << setw(LEFT_JUSTIFIED) << itr->second.artist;
cout << "Rating" << left << setw(LEFT_JUSTIFIED) << itr->second.rating<<endl;
}
cout << "\n";
cout << "Rating Sorted List\n";
sortByRating(songList);
delete newSongNode;
return 0;
}
First of all, you have two variables with similar names, and you definitely misuse them:
SongNode* newSongNode = new SongNode;
// ...
SongNode* newNode = new SongNode;
newNode->title = title;
newNode->artist = artist;
newNode->rating = rating;
songList.insert(pair<string, SongNode>(title, *newSongNode));
You are initializing the newNode but inserting the newSongNode. The values are initialized with empty strings, so that may explain no printing.
As for "searching in a multimap" be more specific in what your problem is.
You are not populating the songList with the SongNode objects that you fill with data. You have an extra SongNode that has no data in it, which is the only object you are putting into the songList. So there is nothing to print.
Try this instead:
#include <iostream>
#include <string>
#include <iterator>
#include <map>
#include <algorithm>
#include <iomanip>
#include <limits>
using namespace std;
struct SongNode {
string title;
string artist;
float rating;
};
//Constants
#define INFINITE_LOOP 1
#define LEFT_JUSTIFIED 30
//Prototypes
void sortByArtist(multimap<string, SongNode>& newSongNode);
void sortByRating(multimap<string, SongNode>& newSongNode);
//FUNCTION : void sortByArtist
//PARAMETER : multimap<string, SongNode>&newSongNode
//RETURN : void
//DESCRIPTION : This function will sort the multimap by the artist of the song
void sortByArtist(multimap<string, SongNode> &newSongNode) {
multimap<string, SongNode> temp;
for (auto &elem : newSongNode)
temp.insert(make_pair(elem.second.artist, elem.second));
newSongNode.clear();
for (auto &elem : temp)
newSongNode.insert(make_pair(elem.second.artist, elem.second));
}
//FUNCTION : void sortByRating
//PARAMETER : (multimap<string, SongNode>& newSongNode
//RETURN : void
//DESCRIPTION : This function will sort the multimap by the rating.
void sortByRating(multimap<string, SongNode>& newSongNode) {
multimap<float, SongNode, greater<int>> temp;
for (auto &elem : newSongNode)
temp.insert(make_pair(elem.second.rating, elem.second));
newSongNode.clear();
for (auto &elem : temp)
newSongNode.insert(make_pair(" ", elem.second));
}
int main() {
multimap<string, SongNode> songList;
string title, artist;
float rating;
cout << "Please enter a title artist and rating\n";
while (INFINITE_LOOP) {
cout << "Title: ";
cin >> title;
if (title == ".") {
break;
}
cout << "Artist: ";
cin >> artist;
cout << "Rating: ";
cin >> rating;
//Error check for rating
while (INFINITE_LOOP) {
if (!cin) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "The rating you have entered is invalid\n";
}
else if (rating < 1.0f) {
cout << "The rating you have entered is less then 1\n";
}
else if (rating > 5.0f) {
cout << "The rating you have to entered is greater then 5\n";
}
else
break;
cout << "Rating: ";
cin >> rating;
}
SongNode newNode;
newNode.title = title;
newNode.artist = artist;
newNode.rating = rating;
songList.insert(make_pair(title, newNode));
}
//display the two lists here.
cout << "Artist Sorted List\n";
sortByArtist(songList);
for (auto &elem : songList) {
cout << "Title" << left << setw(LEFT_JUSTIFIED) << elem.second.title;
cout << "Artist" << left << setw(LEFT_JUSTIFIED) << elem.second.artist;
cout << "Rating" << left << setw(LEFT_JUSTIFIED) << elem.second.rating << endl;
}
cout << "\n";
cout << "Rating Sorted List\n";
sortByRating(songList);
for (auto &elem : songList) {
cout << "Title" << left << setw(LEFT_JUSTIFIED) << elem.second.title;
cout << "Artist" << left << setw(LEFT_JUSTIFIED) << elem.second.artist;
cout << "Rating" << left << setw(LEFT_JUSTIFIED) << elem.second.rating << endl;
}
cout << "\n";
return 0;
}

vector pointers and retrieving data

I'm a beginner at coding in C++ and every other language. The problem I'm having here is in main() with the first (else if) where (UserInput == sell). I would like the function to print the data stored in the object #listPos to retrieve the cost and input it into my incomplete Profit() function, but every time I dereference the pointer (Search) I get an error code. There's something I'm missing big time please help!!
Ive already tried (*search) but there's a huge error code.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class UnSold{
public:
UnSold(string NameOfShoe, int PurchasePrice ){
name = NameOfShoe;
cost = PurchasePrice;
return;
}
void SetName(string NameOfShoe){
name = NameOfShoe;
return;
}
void SetCost(int PurchasePrice){
cost = PurchasePrice;
return;
}
string GetName() const {
return name;
}
int GetCost() const{
return cost;
}
void Profit();
void PrintItem();
private:
string name;
int cost;
};
void UnSold::Profit(){
static int profit = 0;
//profit += (sold-cost);
}
void UnSold::PrintItem(){
cout << "Name: " << this->name << " Cost: " << this->cost << endl;
}
void PrintEverything(vector<UnSold*> AllItems) {
unsigned int i;
for (i=0; i<AllItems.size(); ++i) {
cout<< i+1 << " ";
(*AllItems.at(i)).PrintItem();
}
}
int main(){
vector<UnSold*> Inventory;
string Name;
int Cost;
string UserInput;
unsigned int listPos;
UnSold* newItem = nullptr;
UnSold* search = nullptr;
while ( UserInput != "quit") {
cout << "Do you want to add, sell, print or quit?" <<endl;
cin >> UserInput;
if ( UserInput == "add") {
cout << "Enter item name: "<<endl;
cin >> Name;
cout << "Enter item cost: " << endl;
cin >> Cost;
newItem = new UnSold(Name, Cost);
Inventory.push_back(newItem);
}
else if ( UserInput == "sell") {
cout << "List Positon: ";
cin >> listPos;
if ( listPos < Inventory.size()){
cout << " Item Sold and Removed from list position " << listPos <<endl;
search = Inventory.at(listPos-1);
//cout<< "contents of Search: "<< search << endl;
delete search;
Inventory.erase(Inventory.begin() + (listPos -1));
}
else{
cout << "Error"<<endl;
}
}
else if ( UserInput == "print") {
PrintEverything(Inventory);
}
else if ( UserInput != "quit"){
}
}
return 0;
}
This is a compile error.
Remove line 85: newItem.at(listPos - 1); and it runs just fine in visual studio.
The issue is that newItem is a pointer to an element. I assume you meant to use Inventory here instead. However, that logic was already done on the previous line.
On a side note, I stongly advise against storing owning pointers like this. There's no good reason in this case not to just use vector<UnSold> instead.
else if ( UserInput == "sell") {
cout << "List Positon: ";
cin >> listPos;
if ( listPos < Inventory.size()){
cout << " Item Sold and Removed from list position " << listPos <<endl;
search = Inventory.at(listPos-1);
//cout<< "contents of Search: "<< search << endl;
delete search;
Inventory.erase(Inventory.begin() + (listPos -1));
Here you mix the use of listPos and listPos - 1.
If you're allowing the user to input position 0 indexed, then
Inventory.at(listPos-1) should be Inventory.at(listPos) and
Inventory.erase(Inventory.begin() + (listPos -1)) should be Inventory.erase(Inventory.begin() + (listPos)).
If you're letting them input the position with the indexing starting at 1, then
if (listPos < Inventory.size()) should be
if(listPos <= Inventory.size() && listPos > 0)

Searching for a string in an array

I have "items" in an "inventory" array, the inventory array is a struct composed of several different parts however I want to be able to search for a certain part of the array by using the item name alone (so I can make functions to delete, purchase, etc.) I was wondering how I would go about doing so and if it would instead be easier to convert the struct to a class instead if need be. Keep in mind a good amount of it is still a work in progress, I'm specifically aiming for the removeItem function currently however. Thanks in advance for any and all help!
my code is here:
#include "integerstore.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void removeItem(Item);
int buyItem(Item, int);
int sellItem(Item, int);
void stockReport(Item);
struct Item
{
string name;
float cost;
float price;
int quantity;
};
int main()
{
Item inventory[100];
int total = 0;
string cmd;
cout << "Welcome to inventory management. To add a new inventory item type add, to remove and item from inventory type remove, to add to inventory quantity type buy, to mark a sold item type sell, to see the current inventory report type report and to end the program type stop" << endl;
do
{
cin >> cmd;
if (cmd == "add")
{
cout << "Enter the new item's name";
cin >> inventory[i].name;
cout << endl;
cout << "Enter the new item's cost";
cin >> inventory[i].cost;
if (inventory[i].cost <= 100.00)
{
break;
}
else
{
cout << "Cost of item may not exceed 100.00, please reenter.";
cin.clear();
}
cout << endl;
cout << "Enter the new item's selling price";
cin >> inventory[i].price;
if (inventory[i].price <= 100.00)
{
break;
}
else
{
cout << "Selling price may not exceed 100.00, please reenter.";
cin.clear();
}
cout << endl;
i++;
}
else if (cmd == "remove")
removeItem(inventory[100]);
else if (cmd == "buy")
buyItem(inventory[100], total);
else if (cmd == "sell")
sellItem(inventory[100]);
else if (cmd == "report")
stockReport(inventory[100]);
else if (cmd != "stop")
cout << "invalid";
}
while (cmd != "stop");
system ("pause");
return 0;
}
int buyItem(Item w, int w2)
{
string itemName;
cout << "Enter the item name of which you wish to add more stock to" << endl;
cin >> itemName;
}
int sellItem(Item x, int x2)
{
}
void removeItem (Item y)
{
string itemName;
cout << "Enter the item name you wish to remove from the inventory" << endl;
cin >> itemName;
}
void stockReport(Item z)
{
}
You can use a map<string, Item> (you might want to remove name from the Item struct).
Then you can use it for instance like this:
map<string, Item> inventory;
// Add
inventory["stuff"].cost = 12;
// ...
// Get
string name;
cin >> name;
Item myItem = inventory[name];