I am trying to write a Program to solve the Die Hard Bucket Puzzle, Most of the Code works fine except for the Pour Function which references the class objects.
I have double checked the arrhythmic in the pour function and have checked that the function is reading the correct capacities
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Bucket{
private:
string name;
int capacity, contents;
public:
Bucket(string name_, int capacity_){
name = name_;
capacity = capacity_;
}
void Print(){
cout << "Bucket Name: " << name << endl;
cout << "Capacity: " << capacity << " Gallons" << endl;
cout << "Contents: " << contents << " Gallons" << endl;
}
void Fill(){
contents = capacity;
}
void Empty(){
contents = 0;
}
void Pour(Bucket A){
if (contents + A.contents > A.capacity){
contents -= A.capacity;
A.contents = A.capacity; //Error Here
}
else{
A.contents += contents; //Error Here
contents = 0;
}
}
};
int main(){
Bucket A1("A", 3), A2("B", 5);
int x;
cout << "0 - Exit" << endl << "1 - Fill Bucket A" << endl;
cout << "2 - Empty Bucket A" << endl << "3 - Pour A into B" << endl;
cout << "4 - Fill Bucket B" << endl << "5 - Empty Bucket B" << endl;
cout << "6 - Pour B into A" << endl << "7 - Print" << endl;
cout << "8 - Solve Die Hard Puzzle" << endl;
cin >> x;
while (x != 0){
switch (x){
case 0:{
return 0;
}
case 1:{
A1.Fill();
A1.Print();
cin >> x;
break;
}
case 2:{
A1.Empty();
A1.Print();
cin >> x;
break;
}
case 3:{
A1.Pour(A2);
A1.Print();
A2.Print();
cin >> x;
break;
}
case 4:{
A2.Fill();
A2.Print();
cin >> x;
break;
}
case 5:{
A2.Empty();
A2.Print();
cin >> x;
break;
}
case 6:{
A2.Pour(A2);
A1.Print();
A2.Print();
cin >> x;
break;
}
case 7:{
A1.Print();
A2.Print();
}
case 8:{
A2.Fill();
A2.Pour(A1);
A2.Fill();
A2.Pour(A1);
A2.Print();
}
default:{
cout << "Invailid Input." << endl;
cin >> x;
break;
}
}
}
return 0;
}
The programming outputs the incorrect contents for the bucket being poured into, outputting 0 instead of the actual number
Related
I am using Code::Blocks to write this C++ program, but everytime I do a 3rd Insert on the Link List, and when I use the Display option to check my work, I get a strange error. I have encountered no build errors. Please help check and advise when you have the chance, thank you.
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
typedef struct student
{
string name;
int quiz1, quiz2, quiz3;
struct student *nxt;
} STUDENT;
class studentsStruct
{
private:
STUDENT *S; //Header of the Student List
public:
void init();
void add(string n, int a, int b, int c);
void del(string n);
void update(string n);
void save();
void retrieve();
void display();
};
int menu();
int updatemenu();
float round2(float x); // function to round the average and limit to 2 decimal points
int main()
{
studentsStruct ars;
string nm;
int a, b, c;
ars.init(); // Initialize the S Header of the Student List
ars.retrieve(); // Check if the "studentsdb.txt" is available and load the data as needed
while (1)
{
switch (menu())
{
case 1:
system("cls");
cout << "Insert Mode" << endl;
cout << "Name: ";
cin >> nm;
cout << "Input Quiz 1: ";
cin >> a;
cout << "Input Quiz 2: ";
cin >> b;
cout << "Input Quiz 3: ";
cin >> c;
ars.add(nm, a, b, c);
break;
case 2:
system("cls");
cout << "Update Mode" << endl;
cout << "Input Students Name: ";
cin >> nm;
ars.update(nm);
break;
case 3:
system("cls");
cout << "Delete Mode" << endl;
cout << "Enter Name: ";
cin >> nm;
ars.del(nm);
break;
case 4:
ars.display();
break;
case 5:
ars.save();
exit(0);
default:
cout << "1 to 5 only. ";
system("pause");
}
}
return 0;
}
void studentsStruct::init()
{
S = NULL;
}
void studentsStruct::add(string n, int a, int b, int c)
{
STUDENT *p, *q, *temp;
p = q = S;
temp = new STUDENT;
temp->name = n;
temp->quiz1 = a;
temp->quiz2 = b;
temp->quiz3 = c;
while (p != NULL)
{
q = p;
p = p->nxt;
}
if (p == S)
{
S = temp;
}
else
{
q->nxt = temp;
temp->nxt = p;
}
}
void studentsStruct::del(string n)
{
STUDENT *p, *q;
p = q = S;
while (p != NULL && p->name != n)
{
q = p;
p = p->nxt;
}
if (p == NULL)
{
cout << n << (" is not found.") << endl;
system("pause");
}
else
{
if (p == S)
{
S = S->nxt;
}
else
{
q->nxt = p->nxt;
delete (p);
cout << n << (" is deleted from the student records") << endl;
}
}
}
void studentsStruct::update(string n)
{
STUDENT *p, *q;
p = q = S;
int ua, ub, uc;
while (p != NULL && p->name != n)
{
q = p;
p = p->nxt;
}
if (p == NULL)
{
cout << ("Not Found") << endl;
system("pause");
}
else
{
while (1)
{
cout << "Update Mode" << endl;
cout << "Student : " << p->name << endl;
cout << "Quiz 1 Grade: " << p->quiz1 << endl;
cout << "Quiz 2 Grade: " << p->quiz2 << endl;
cout << "Quiz 3 Grade: " << p->quiz3 << endl;
switch (updatemenu())
{
case 1:
cout << "Quiz 1 Grade: ";
cin >> ua;
p->quiz1 = ua;
save();
break;
case 2:
cout << "Quiz 2 Grade: ";
cin >> ub;
p->quiz2 = ub;
save();
break;
case 3:
cout << "Quiz 3 Grade: ";
cin >> uc;
p->quiz3 = uc;
save();
break;
case 4:
main();
save();
break;
default:
cout << "Select an option between 1 to 3" << endl;
cout << "or select 4 to exit the Update Menu: " << endl;
}
}
}
}
int updatemenu()
{
int um;
cout << "Update Menu" << endl;
cout << "1.) Update Quiz 1 Grade" << endl;
cout << "2.) Update Quiz 2 Grade" << endl;
cout << "3.) Update Quiz 3 Grade" << endl;
cout << "4.) Return to the Main Menu" << endl;
cout << "Select an option between 1 to 3" << endl;
cout << "or select 4 to exit the Update Menu: ";
cin >> um;
return (um);
}
void studentsStruct::display()
{
STUDENT *p;
int i = 1;
p = S;
float ave;
string remarks;
system("cls");
cout << "No.\tName\tQuiz 1\tQuiz 2\tQuiz 3\tAverage\tRemarks\n";
while (p != NULL)
{
ave = (p->quiz1 + p->quiz2 + p->quiz3) / 3.0;
remarks = ave >= 75 ? "Passed" : "Failed";
cout << i++ << ".)\t" << p->name << "\t" << p->quiz1 << "\t" << p->quiz2 << "\t" << p->quiz3 << "\t" << round2(ave) << "\t" << remarks << endl;
p = p->nxt;
}
system("pause");
}
int menu()
{
int op;
cout << "Menu" << endl;
cout << "1.) Insert" << endl;
cout << "2.) Update" << endl;
cout << "3.) Delete" << endl;
cout << "4.) Display" << endl;
cout << "5.) Exit" << endl;
cout << "Select(1-5): ";
cin >> op;
return (op);
}
// Save the student data to "studentdb.txt" if available and create a file if needed
void studentsStruct::save()
{
STUDENT *p;
p = S;
ofstream stuData;
stuData.open("studentdb.txt");
while (p != NULL)
{
stuData << p->name << " " << p->quiz1 << " " << p->quiz2 << " " << p->quiz3 << endl;
p = p->nxt;
}
stuData.close();
}
// Check if the "studentdb.txt" is available and load the data as needed
void studentsStruct::retrieve()
{
ifstream fp;
string n;
int ax, by, cz;
fp.open("studentdb.txt");
if (fp.peek() != std::ifstream::traits_type::eof())
{
while (fp >> n >> ax >> by >> cz)
{
add(n, ax, by, cz);
}
}
else
{
cout << "The file is available but contains no records" << endl;
}
fp.close();
}
// function to round the average and limit to 2 decimal points
float round2(float x)
{
return trunc(x * 100.0) / 100.0;
}
And this is the error I am encountering (see screenshot below):
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
// these should have all of my declared functions
int start(char x, char y, char z);
void pim();
void pmm();
void login();
void createa();
//my assignment wants me to have only one function used
int main()
{
start(pim(), login(), createa());
return 0;
}
//This should be the start of the code
void pim()
{
cout << "Please select a letter from the menu below:" << endl;
cout << "l - Login" << endl;
cout << "c - Create New Account" << endl;
cout << "q - Quit" << endl;
}
// this is to post a menu after you make the first choice above
void pmm()
{
cout << "d - Deposit Money" << endl;
cout << "w - Withdraw Money" << endl;
cout << "r - Request Balance" << endl;
cout << "q - Quit" << endl;
}
//this is to login to the account
void login()
{
cout << "Okay, you're in" << endl;
}
// this is to create an account
void createa()
{
int id = 0;
int password = 0;
cout << "create an ID of two numbers" << endl;
cin >> id;
cout << "Make a password of 4 numbers" << endl;
cin >> password;
}
// Starts and is basically the entire project
int start(char x, char y, char z)
{
char pim = x;
cout << pim;
int choice = 0;
char select = '\0';
cout << "Enter the choice that you want:";
cin >> choice;
if(select == 'l')
{
choice = 1;
}
else if( select == 'c')
{
choice = 2;
}
else
{
choice = 3;
}
switch (choice)
{
case 1:
cout << y << endl;
break;
case 2:
cout << z << endl;
break;
case 3:
exit(0);
break;
default:
cout << "This is not a command" << endl;
}
return 0;
}
I think what you are looking for is function pointers, eg:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
// these should have all of my declared functions
int start(void (*x)(), void (*y)(), void (*z)());
void pim();
void pmm();
void login();
void createa();
//my assignment wants me to have only one function used
int main()
{
start(&pim, &login, &createa);
return 0;
}
//This should be the start of the code
void pim()
{
cout << "Please select a letter from the menu below:" << endl;
cout << "l - Login" << endl;
cout << "c - Create New Account" << endl;
cout << "q - Quit" << endl;
}
// this is to post a menu after you make the first choice above
void pmm()
{
cout << "d - Deposit Money" << endl;
cout << "w - Withdraw Money" << endl;
cout << "r - Request Balance" << endl;
cout << "q - Quit" << endl;
}
//this is to login to the account
void login()
{
cout << "Okay, you're in" << endl;
}
// this is to create an account
void createa()
{
int id = 0;
int password = 0;
cout << "create an ID of two numbers" << endl;
cin >> id;
cout << "Make a password of 4 numbers" << endl;
cin >> password;
}
// Starts and is basically the entire project
int start(void (*x)(), void (*y)(), void (*z)())
{
x();
char choice = '\0';
cout << "Enter the choice that you want:";
cin >> choice;
switch (choice)
{
case 'l':
y();
break;
case 'c':
z();
break;
case 'q':
exit(0);
break;
default:
cout << "This is not a command" << endl;
}
return 0;
}
However, unless "function pointers" is the actual topic you are studying at the moment, then this is a very questionable design, even for a simple homework assignment. It would be cleaner and easier to read/manage to just call the functions directly instead, eg:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
// these should have all of my declared functions
int start();
void pim();
void pmm();
void login();
void createa();
//my assignment wants me to have only one function used
int main()
{
start();
return 0;
}
//This should be the start of the code
void pim()
{
cout << "Please select a letter from the menu below:" << endl;
cout << "l - Login" << endl;
cout << "c - Create New Account" << endl;
cout << "q - Quit" << endl;
}
// this is to post a menu after you make the first choice above
void pmm()
{
cout << "d - Deposit Money" << endl;
cout << "w - Withdraw Money" << endl;
cout << "r - Request Balance" << endl;
cout << "q - Quit" << endl;
}
//this is to login to the account
void login()
{
cout << "Okay, you're in" << endl;
}
// this is to create an account
void createa()
{
int id = 0;
int password = 0;
cout << "create an ID of two numbers" << endl;
cin >> id;
cout << "Make a password of 4 numbers" << endl;
cin >> password;
}
// Starts and is basically the entire project
int start()
{
pim();
char choice = '\0';
cout << "Enter the choice that you want:";
cin >> choice;
switch (choice)
{
case 'l':
login();
break;
case 'c':
createa();
break;
case 'q':
exit(0);
break;
default:
cout << "This is not a command" << endl;
}
return 0;
}
I am creating a program to modify the records in a binary file. But i always end up creating two similar records.
I copy all the data to another file. if I find the record to be modified, I read the modified data and copy it to the new file. When all the records are copied, The remporary file is renamed
The class:
class student
{
char name[200];
int rno;
float marks;
char grad;
void grade()
{
if(marks < 33)
grad = 'F';
else if(marks < 50)
grad = 'D';
else if(marks < 60)
grad = 'C';
else if(marks < 80)
grad = 'B';
else
grad = 'A';
}
public:
void get()
{
fflush(stdin);
cout << "Name: ";
gets(name);
cout << "Roll number: ";
cin >> rno;
cout << "Marks:" ;
cin >> marks;
grade();
}
///////////////////////////////////////////////////////////
void showname()
{
cout << "Name: " << name << endl;
}
///////////////////////////////////////////////////////////
void show()
{
cout << "Name: " << name << endl;
cout << "Roll number: " << rno << endl;
cout << "Marks: " << marks << endl;
cout << "Grade: " << grad << endl;
}
///////////////////////////////////////////////////////////
int get_rno()
{
return rno;
}
////////////////////////////////////////////////////////////
float get_marks()
{
return marks;
}
////////////////////////////////////////////////////////////
char get_grade()
{
return grad;
}
////////////////////////////////////////////////////////////
char* getname()
{
return name;
}
};
The modify function:
void modify_rec()
{
int rno;
ifstream fin("stu.dat",ios::binary);
ofstream fout("modif.dat",ios::binary);
student s;
cout << "Enter the roll number whose details you want to edit:";
cin >> rno;
while(!fin.eof())
{
if(fin.eof())
break;
fin.read((char*)&s, sizeof(s));
if(s.get_rno() == rno)
{
s.get();
fout.write((char*)&s, sizeof(s));
rno = -1;
}
else
{
fout.write((char*)&s, sizeof(s));
}
}
fin.close();
fout.close();
remove("stu.dat");
rename("modif.dat","stu.dat");
}
Main function:
int main()
{
char op;
int ch;
do
{
system("CLS");
cout << "Select an option:" << endl;
cout << "\t1.)Add record." << endl;
cout << "\t2.)Display all." << endl;
cout << "\t3.)Search by roll number." << endl;
cout << "\t4.)Search by name" << endl;
cout << "\t5.)Modify record." << endl;
cout << "\t6.)Delete record." << endl;
cout << "\t7.)Display list of distinction holders." << endl;
cout << "\t8.)Create list of failures." << endl;
cout << "\t9.)Display report card." << endl;
cin >> ch;
switch(ch)
{
case 1: add_rec(); break;
case 2: disp_all(); break;
case 3: search_rno(); break;
case 4: search_name(); break;
case 5: modify_rec(); break;
case 6: delete_rec(); break;
case 7: disp_distinction(); break;
case 8: create_failure(); break;
case 9: disp_repcrd(); break;
}
cout << "Do you want to continue?" << endl;
cin >> op;
}while(tolower(op) == 'y');
}
In the adding user section in the code below, I am unable to type any characters for the "Add another person?(y/n): " question. it just jumps back to entering age. How do I fix this?
I've tried to change ans into a string, implement a while loop to force the question to show up, and many other things. It just seems that nothing works and I've been trying it for the good part of two hours
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main()
{
char ans;
int people;
int option;
int count = 0;
struct data
{
string name;
int age;
char gender;
string comments;
}person[100];
// homescreen
homescreen:
cout << "Welcome to the Data Base!" << endl;
cout << endl;
// displaying all people
for (int list = 0; list < count; list++)
{
cout << list << ".) " << person[list].name << endl;
}
cout << endl;
cout << "[1] View Person" << endl;
cout << "[2] Add Person" << endl;
cout << "[3] Edit Person" << endl;
cout << "[4] Delete Person" << endl;
cout << "[5] Exit" << endl;
cout << "Choose Option: "; cin >> option;
// using options
while (option != 5)
{
if (option == 1)
{
view:
for (int list2 = 0; list2 < count; list2++)
{
cout << list2 << ".) " << person[list2].name << endl;
}
cout << endl;
cout << "Enter number of person you want: "; cin >> people;
system("cls");
cout << "Name: " << person[count].name << endl;
cout << "Age: " << person[count].age << endl;
cout << "Gender: " << person[count].gender << endl;
cout << "Comments: " << person[count].comments << endl << endl;
cout << "View another person?(y/n): "; cin >> ans;
if (ans == 'y')
{
system("cls"); goto view;
}
else if (ans == 'n')
{
system("cls"); goto homescreen;
}
}
if (option == 2)
{
add:
system("cls");
cout << "Name: "; cin >> person[count].name;
system("cls");
cout << "Age: "; cin >> person[count].age;
system("cls");
cout << "Gender(M/F/H): "; cin >> person[count].gender;
system("cls");
cout << "Comments: "; cin >> person[count].comments;
count++;
system("cls");
cout << "Add another person?(y/n): "; cin >> ans;
if (ans == 'y')
{
system("cls");
goto add;
}
else if (ans == 'n')
{
system("cls");
goto homescreen;
}
}
}
}
If you anybody can help me I'd be grateful
The goto statements in your code makes the program really good
spaghetti
structure and that is not
good.
Therefore, think instead of goto other options, such as infinite
while loop which will break once the user enters the n or moving
the code to the function.
Secondly what if you have not entered any persons and choosing the
option 1. You still output the attributes of the person as
count is initialized zero at least. Remember the attributes are
not initialized at this point. Accessing the uninitialized
variables will invoke undefined
behavior. Therefore,
provide a check (something like if(count > 0) )before you execute the code in option 1.
In addition to that, remember that
std::endl flushes the output buffer, and '\n' doesn't. Therefore, most of
the cases you might wanna use just
\n.
Last but not the least, use std::vector instead of the using C style arrays with some predefined size. What if the user has more than 100 inputs? The solution in C++ is std::vector, which can expand dynamically as its storage is handled automatically.
Following is a possible solution to your program, in which the comments will guide you through to the things that I mentioned above.
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
struct Data
{
std::string name;
int age;
char gender;
std::string comments;
Data(const std::string& n, int a, char g, const std::string& c) // provide a Constructor
:name(n), age(a), gender(g), comments(c)
{}
};
void debugMsg(const std::string& msg)
{
system("cls");
std::cout << "\n\n\t\t" << msg << "\n\n";
Sleep(3000);
}
int main()
{
std::vector<Data> person; // use std::vector to store the datas
while (true) // loop: 1
{
system("cls");
std::cout << "Welcome to the Data Base! \n\n";
std::cout << "[1] View Person\n";
std::cout << "[2] Add Person\n";
std::cout << "[3] Edit Person\n";
std::cout << "[4] Delete Person\n";
std::cout << "[5] Exit\n";
std::cout << "Choose Option: ";
int option; std::cin >> option;
switch (option) // use switch to validate the options
{
case 1:
{
while (true) // loop - 2 -> case 1
{
// if no data available to show -> just break the loop 2 and return to the outer loop(i.e, loop 1)
if (person.empty()) { debugMsg("No person available to show ....going to main manu...."); break; }
// otherwise: displaying all people
for (std::size_t index = 0; index < person.size(); ++index)
std::cout << index << ".) " << person[index].name << "\n";
std::cout << "\nEnter number of person you want: ";
std::size_t index; std::cin >> index;
// if the index is not valid -> just break the loop 2 and return to the outer loop(i.e, loop 1)
if (index < 0 || index >= person.size()) { debugMsg("Sorry, wrong index!... returning to the main menu......"); break; }
system("cls");
std::cout << "Name: " << person[index].name << std::endl;
std::cout << "Age: " << person[index].age << std::endl;
std::cout << "Gender: " << person[index].gender << std::endl;
std::cout << "Comments: " << person[index].comments << std::endl << std::endl;
std::cout << "View another person?(y/n): ";
char ans; std::cin >> ans;
if (ans == 'y') { system("cls"); continue; } // just continue looping
else if (ans == 'n') { break; } // this will break the loop 2 and return to the outer loop(i.e, loop 1)
else { debugMsg("Sorry, wrong option!... returning to the main menu......"); break; }
}
} break;
case 2:
{
while (true) // loop - 3 -> case 2
{
system("cls");
std::string name, comments; int age; char gender;
std::cout << "Name: "; std::cin >> name;
std::cout << "Age: "; std::cin >> age;
std::cout << "Gender(M/F/H): "; std::cin >> gender;
std::cout << "Comments: "; std::cin >> comments;
// simply construct the Data in person vector in place
person.emplace_back(name, age, gender, comments);
std::cout << "\n\nAdd another person?(y/n): ";
char ans; std::cin >> ans;
if (ans == 'y') { system("cls"); continue; }
else if (ans == 'n') { system("cls"); break; } // same as case 1
else { debugMsg("Sorry, wrong option!... returning to the main menu......"); break; }
}
} break;
case 3: { /*code*/ debugMsg("Sorry, Not implemented!... returning to the main menu......"); } break;
case 4: { /*code*/ debugMsg("Sorry, Not implemented!... returning to the main menu......"); } break;
case 5: return 0; // if its 5, just retun the main
default: break;
}
}
return 0;
}
As mentioned above, using "goto" is a bad style, so i would suggest structure your program a little. Below is my version.
Naturally, I did not add any checks and controls, the author will be able to do this on his own. But main logics should work. And, of course, it is better to use vector instead of static array.
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
enum options { OPT_VIEW = 1, OPT_ADD = 2, OPT_EDIT = 3, OPT_DELETE = 4, OPT_EXIT = 5 };
struct data
{
string name;
int age;
char gender;
string comments;
};
class App
{
private:
data person[100];
int count = 0;
public:
App();
void Run();
int HomeScreen();
void View();
void Add();
};
App::App() : count(0)
{}
void App::Run()
{
int option = HomeScreen();
while(option != OPT_EXIT)
{
switch(option)
{
case OPT_VIEW:
View();
break;
case OPT_ADD:
Add();
break;
}
option = HomeScreen();
}
}
int App::HomeScreen()
{
int option = 0;
cout << "Welcome to the Data Base!" << endl;
cout << endl;
// displaying all people
for(int list = 0; list < count; list++)
{
cout << list << ".) " << person[list].name << endl;
}
cout << endl;
cout << "[1] View Person" << endl;
cout << "[2] Add Person" << endl;
cout << "[3] Edit Person" << endl;
cout << "[4] Delete Person" << endl;
cout << "[5] Exit" << endl;
cout << "Choose Option: "; cin >> option;
return option;
}
void App::View()
{
char ans = 0;
do
{
int people = 0;
for(int list2 = 0; list2 < count; list2++)
{
cout << list2 << ".) " << person[list2].name << endl;
}
cout << endl;
cout << "Enter number of person you want: "; cin >> people;
system("cls");
cout << "Name: " << person[people].name << endl;
cout << "Age: " << person[people].age << endl;
cout << "Gender: " << person[people].gender << endl;
cout << "Comments: " << person[people].comments << endl << endl;
cout << "View another person?(y/n): "; cin >> ans;
}
while(ans == 'y');
system("cls");
}
void App::Add()
{
char ans = 0;
do
{
system("cls");
cout << "Name: "; cin >> person[count].name;
system("cls");
cout << "Age: "; cin >> person[count].age;
system("cls");
cout << "Gender(M/F/H): "; cin >> person[count].gender;
system("cls");
cout << "Comments: "; cin >> person[count].comments;
count++;
system("cls");
cout << "Add another person?(y/n): "; cin >> ans;
}
while(ans == 'y');
system("cls");
}
int main()
{
App program;
program.Run();
}
i need help. I have an array of 10, and it consists of a string and a value initialized to it. My question is how i can ask the user to input how much more to add or how much to remove. then display the updated list.
for example choose valve, then add 2 more, which will make it 12, then display the updated array with the other arrays. i need to pass it through a function also. please and thank you for the help in advance, here it my code so far. Feel free to criticize as much as you guys would like. It will only help me get better :)
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <cstring>
#include <string>
using namespace std;
//define Structure as invParts
struct invParts{
string name;
int qty;
};
void addparts(invParts *&c,int);
void removeparts(invParts *&c, int);
int main()
{
invParts *descrip;
int row = 0;
char choice;
invParts bin[10]= { {"valve",10}, {"Bearing",5}, {"Bushing",21},
{"Coupling",7}, {"Flange",5}, {"Gear",5},
{"Gear House", 5}, {"Vacuum Gripper", 25},
{"Cable",18}, {"Rod",12}, };
cout<<"-----------------------------------------------------" << endl;
cout<<"Part Description" << " " << "Number of parts in the bin" << endl;
cout <<"----------------------------------------------------" << endl;
cout << endl;
for(row = 0; row < 10; row++)
{
cout << setw(11)<< left <<bin[row].name << setw(25) << right << bin[row].qty<< endl;
}
cout << endl;
cout << "Here are 3 options" << endl;
cout << "Type A , to Add parts" << endl;
cout << "Type R , to Remove parts" << endl;
cout << "Type E, to Exit Program" << endl;
cout << "Choose your option: ";
cin >> choice;
cout << endl;
switch (choice)
{
int num;
case 'A' :
case 'a' : cout <<"You will now add" << endl;
addparts(descrip,num);
break;
case 'R':
case 'r': cout <<"You will now remove" << endl;
//removeparts(descrip,num);
break;
case 'E':
case 'e': cout<<"Now exiting program" << endl;
exit(0);
}
system("pause");
return 0;
}
void addparts(invParts *&c,int number)
{
string what;
int n;
cout <<"Which part? " << endl;
cin >> what;
//am i doing this right?
if ( what == "valve" || what == "Valve")
cout <<"How much do you want to add? "<<endl;
cin >> n;
}
/*void removeparts(invParts *&c, int)
{
//you guys can show me how to do the add, i can do the remove
}
*/
You are using the wrong data structure to capture the inventory. You need something like
typedef std::map<std::string, int> Inventory;
Here's an updated version of your program.
#include <iostream>
#include <string>
#include <iomanip>
#include <map>
using namespace std;
typedef std::map<std::string, int> Inventory;
void initializeInventory(Inventory& inv);
void displayInventory(Inventory const& inv);
void addparts(Inventory& inv);
void removeparts(Inventory& inv);
int main()
{
Inventory inv;
char choice;
initializeInventory(inv);
displayInventory(inv);
while ( true )
{
cout << "Here are 3 options" << endl;
cout << "Type A , to Add parts" << endl;
cout << "Type R , to Remove parts" << endl;
cout << "Type E, to Exit Program" << endl;
cout << "Choose your option: ";
cin >> choice;
cout << endl;
switch (choice)
{
case 'A' :
case 'a' : cout <<"You will now add" << endl;
addparts(inv);
break;
case 'R':
case 'r': cout <<"You will now remove" << endl;
//removeparts(inv);
break;
case 'E':
case 'e': cout<<"Now exiting program" << endl;
exit(0);
}
displayInventory(inv);
}
return 0;
}
void initializeInventory(Inventory& inv)
{
inv["Valve"] = 10;
inv["Bearing"] = 5;
inv["Bushing"] = 21;
inv["Coupling"] = 7;
inv["Flange"] = 5;
inv["Gear"] = 5;
inv["Gear House"] = 5;
inv["Vacuum Gripper"] = 25;
inv["Cable"] = 18;
inv["Rod"] = 12;
}
void displayInventory(Inventory const& inv)
{
cout<<"-----------------------------------------------------" << endl;
cout<<"Part Description" << " " << "Number of parts in the bin" << endl;
cout <<"----------------------------------------------------" << endl;
cout << endl;
for (auto item : inv )
{
cout << setw(15) << left << item.first << setw(25) << right << item.second << endl;
}
cout << endl;
}
void addparts(Inventory& inv)
{
string what;
int n;
cout <<"Which part? " << endl;
cin >> what;
//am i doing this right?
Inventory::iterator iter = inv.find(what);
if ( iter == inv.end() )
{
cout << "There is no such part in the inventory.\n";
return;
}
cout <<"How much do you want to add? "<<endl;
cin >> n;
iter->second += n;
}
void removeparts(Inventory& inv)
{
// ????
}
Update
The inventory can be initialized using:
Inventory inv = { {"Valve",10}, {"Bearing",5}, {"Bushing",21},
{"Coupling",7}, {"Flange",5}, {"Gear",5},
{"Gear House", 5}, {"Vacuum Gripper", 25},
{"Cable",18}, {"Rod",12} };
There is no need for a separate function to initialize the inventory.