SlideShare a Scribd company logo
1 of 6
(C++)Why does this code shows a run time error ? I would like some suggestions, and
corrections.Thanks
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <iomanip>
#include <array>
#include <ctime>
#include <limits>
// <limits>:library used to define and access various properties of numerical
// data types
//(such as the maximum and minimum values)
using namespace std;
class Snack {
private:
string snackName;
double priceSnack;
int snackQuantity;
int sold;
string* transaction;
string getCurrentTime()
{
time_t t = time(0);
struct tm ts;
char buff[10];
ts = *localtime(&t);
strftime(buff, sizeof(buff), "%X", &ts);
return buff;
}
public:
Snack() { // Default constructor
snackName = "";
priceSnack = 0;
snackQuantity = 0;
sold = 0;
transaction = nullptr;
}
Snack(string name, double price, int quant)//Overload cosntructor
{
snackName = name;
priceSnack = price;
snackQuantity = quant;
transaction = new string[quant];
for (int i = 0; i < quant; i++)
transaction[i] = "";
}
// Creating accessor methods
void setName(string s) {
if (s.length() <= 0) {
cout << "Please enter a name" << endl;
}
else
snackName = s;
}
void setPrice(double pr) {
if (pr <= 0) {
cout << "Please enter a price greater than 0" << endl;
}
else
priceSnack = pr;
}
void setQuantity(int qt)
{
if (qt <= 0) {
cout << "Please enter number greater than 0" << endl;
}
else {
snackQuantity = qt;
transaction = new string[qt];
for (int i = 0; i < qt; i++)
transaction[i] = "";
}
}
// Creatting getters
string getName() const {
return snackName;
}
int getInStock() const {
return snackQuantity;
}
int getSold() const {
return sold;
}
double getPrice() const {
return priceSnack;
}
bool buyItem(double& moneyEntered) {
if (snackQuantity == 0) {
cout << "Error: item is sold-out" << endl;
return false;
}
if (moneyEntered >= priceSnack) {
moneyEntered -= priceSnack;
transaction[sold] = getCurrentTime();
snackQuantity--;
sold++;
cout << "Item has been dispensed below" << endl;
return true;
}
else if (moneyEntered < priceSnack) {
if (moneyEntered < 0) {
cout << "Please enter a number greater than 0" << endl;
}
else {
cout << "Amount is less than the price $" << priceSnack << endl;
}
return false;
}
}
~Snack() // Destructor
{
if (sold)
{
cout << "nClosing details for " << snackName << "n";
cout << "ntNumber of sold: " << priceSnack;
cout << "ntProfit Gained: " << priceSnack * snackQuantity << "nn";
for (int i = 0; i < sold; i++) {
cout << "t" << transaction[i] << endl;
}
}
delete[] transaction;
transaction = nullptr;
cout << endl;
}
};
void displayVendingMachine(const Snack[], const int);
int getQuarters();
void userBuyItem(Snack[], const int);
bool promptToContinue();
int main()
{
const int SNACK_MAX = 3;
Snack snack[SNACK_MAX] = { Snack(), Snack("Candy", 1.25,5), Snack("Soda",1.00,2) };
snack[0].setName("Chips");
snack[0].setPrice(1.75);
snack[0].setQuantity(3);
cout << "Welcome to the vender machine!nn";
do
{
userBuyItem(snack, SNACK_MAX);
} while (promptToContinue());
}
// Function for formatting
void displayVendingMachine(const Snack snacks[], int size) {
cout << "Welcome to the Snack Vending Machine!" << endl;
cout << setw(54) << setfill('-') << "-" << setfill(' ') << endl;
cout << setw(5) << "Item #" << setw(20) << "Item Name" << setw(13) << "Price" << setw(14)
<< "# in Stock" << endl;
cout << setw(54) << setfill('-') << "-" << setfill(' ') << endl;
for (int i = 0; i < size; i++) {
cout << setw(5) << i + 1 << setw(20) << snacks[i].getName() << setw(10) << "$"
<< fixed << setprecision(2) << snacks[i].getPrice() << setw(10) << snacks[i].getInStock();
cout << endl;
}
cout << setw(54) << setfill('-') << "-" << setfill(' ') << endl;
cout << endl;
}
// Function to validate the quarters
int getQuarters()
{
int quarter;
// Continuously prompt the user until they enter a valid input
while (true) {
cout << "Enter a number of quarters: ";
cin >> quarter;
// Check if the user entered an invalid input (not a positive integer)
if (cin.fail() || quarter < 1) {
cout << "Invalid input. Enter a positive integer value greater than or"
<< " equal to 1: n";
// Clear the error flags in the cin stream
cin.clear();
// Ignore any remaining characters in the input buffer
cin.ignore(numeric_limits<streamsize>::max(), 'n');
continue;
}
// If a valid input was entered, exit the loop
break;
}
return quarter;
}
void userBuyItem(Snack snack[], const int size)
{
displayVendingMachine(snack,size);
int quarter = getQuarters();
int userInput;
double money;
cout << "Amount entered: " << quarter * 0.25 << endl;
money = quarter * 0.25;
while (true)
{
cout << endl << "Enter a number between 1 and " << size <<
" to make your selection: ";
cin >> userInput;
if (cin.fail() || userInput < 1 || userInput > size)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << "Error: enter a number between 1 and " << size << ": ";
continue;
}
break;
}
snack[userInput - 1].buyItem(money);
if (money > 0)
cout << "$" << money << " dispensedn";
}
bool promptToContinue()
{
char choice;
cout << endl << "Continue? (Y / N): ";
cin >> choice;
if (choice == 'Y' || choice == 'y')
return true;
return false;
}

More Related Content

Similar to (C++)Why does this code shows a run time error - I would like some sug.docx

So I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfSo I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfarjuncollection
 
Please use the code below and make it operate as one program- Notating.pdf
Please use the code below and make it operate as one program- Notating.pdfPlease use the code below and make it operate as one program- Notating.pdf
Please use the code below and make it operate as one program- Notating.pdfseoagam1
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfyamew16788
 
ch5_additional.ppt
ch5_additional.pptch5_additional.ppt
ch5_additional.pptLokeshK66
 
i need to modify this c++ so when the user enter services thats not an.docx
i need to modify this c++ so when the user enter services thats not an.docxi need to modify this c++ so when the user enter services thats not an.docx
i need to modify this c++ so when the user enter services thats not an.docxhendriciraida
 
i need to write a return type function that takes information about th.docx
i need to write a return type function that takes information about th.docxi need to write a return type function that takes information about th.docx
i need to write a return type function that takes information about th.docxhendriciraida
 
I have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfI have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfshreeaadithyaacellso
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfHIMANSUKUMAR12
 
Tugas praktikukm pemrograman c++
Tugas praktikukm  pemrograman c++Tugas praktikukm  pemrograman c++
Tugas praktikukm pemrograman c++Dendi Riadi
 
i want to add to this c++ code a condition so that you can only chose.docx
i want to add to this c++ code a condition so that you can only chose.docxi want to add to this c++ code a condition so that you can only chose.docx
i want to add to this c++ code a condition so that you can only chose.docxhendriciraida
 
#include iostream #include string #include invalidHr.h.pdf
 #include iostream #include string #include invalidHr.h.pdf #include iostream #include string #include invalidHr.h.pdf
#include iostream #include string #include invalidHr.h.pdfAPMRETAIL
 
WEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bcaWEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bcaYashKoli22
 

Similar to (C++)Why does this code shows a run time error - I would like some sug.docx (20)

C++ file
C++ fileC++ file
C++ file
 
So I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfSo I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdf
 
Please use the code below and make it operate as one program- Notating.pdf
Please use the code below and make it operate as one program- Notating.pdfPlease use the code below and make it operate as one program- Notating.pdf
Please use the code below and make it operate as one program- Notating.pdf
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
ch5_additional.ppt
ch5_additional.pptch5_additional.ppt
ch5_additional.ppt
 
i need to modify this c++ so when the user enter services thats not an.docx
i need to modify this c++ so when the user enter services thats not an.docxi need to modify this c++ so when the user enter services thats not an.docx
i need to modify this c++ so when the user enter services thats not an.docx
 
i need to write a return type function that takes information about th.docx
i need to write a return type function that takes information about th.docxi need to write a return type function that takes information about th.docx
i need to write a return type function that takes information about th.docx
 
Project in programming
Project in programmingProject in programming
Project in programming
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
oodp elab.pdf
oodp elab.pdfoodp elab.pdf
oodp elab.pdf
 
I have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfI have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdf
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
 
Tugas praktikukm pemrograman c++
Tugas praktikukm  pemrograman c++Tugas praktikukm  pemrograman c++
Tugas praktikukm pemrograman c++
 
Railwaynew
RailwaynewRailwaynew
Railwaynew
 
C++ file
C++ fileC++ file
C++ file
 
i want to add to this c++ code a condition so that you can only chose.docx
i want to add to this c++ code a condition so that you can only chose.docxi want to add to this c++ code a condition so that you can only chose.docx
i want to add to this c++ code a condition so that you can only chose.docx
 
C++ practical
C++ practicalC++ practical
C++ practical
 
DataTypes.ppt
DataTypes.pptDataTypes.ppt
DataTypes.ppt
 
#include iostream #include string #include invalidHr.h.pdf
 #include iostream #include string #include invalidHr.h.pdf #include iostream #include string #include invalidHr.h.pdf
#include iostream #include string #include invalidHr.h.pdf
 
WEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bcaWEB DESIGN PRACTICLE bca
WEB DESIGN PRACTICLE bca
 

More from asser7

1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf
1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf
1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdfasser7
 
1-) What are the eight subfields of physical geography and what do the.pdf
1-) What are the eight subfields of physical geography and what do the.pdf1-) What are the eight subfields of physical geography and what do the.pdf
1-) What are the eight subfields of physical geography and what do the.pdfasser7
 
1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf
1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf
1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdfasser7
 
1-) What are the eight subfields of physical geography and what do the.pdf
1-) What are the eight subfields of physical geography and what do the.pdf1-) What are the eight subfields of physical geography and what do the.pdf
1-) What are the eight subfields of physical geography and what do the.pdfasser7
 
1- Remember that enzymes (biological catalysts) are most often ______-.pdf
1- Remember that enzymes (biological catalysts) are most often ______-.pdf1- Remember that enzymes (biological catalysts) are most often ______-.pdf
1- Remember that enzymes (biological catalysts) are most often ______-.pdfasser7
 
1- Pick any current Canadian political party of your choice (whether i.pdf
1- Pick any current Canadian political party of your choice (whether i.pdf1- Pick any current Canadian political party of your choice (whether i.pdf
1- Pick any current Canadian political party of your choice (whether i.pdfasser7
 
1- Research Certificate based authentication techniques -& research On.pdf
1- Research Certificate based authentication techniques -& research On.pdf1- Research Certificate based authentication techniques -& research On.pdf
1- Research Certificate based authentication techniques -& research On.pdfasser7
 
1- What is the history and evolution of government involvement in heal.pdf
1- What is the history and evolution of government involvement in heal.pdf1- What is the history and evolution of government involvement in heal.pdf
1- What is the history and evolution of government involvement in heal.pdfasser7
 
1- What is the difference between a cell membrane and a cell wall- Des.pdf
1- What is the difference between a cell membrane and a cell wall- Des.pdf1- What is the difference between a cell membrane and a cell wall- Des.pdf
1- What is the difference between a cell membrane and a cell wall- Des.pdfasser7
 
14- What is Big-O notation- Give example algorithm for O(1)-O(n)-O(log.pdf
14- What is Big-O notation- Give example algorithm for O(1)-O(n)-O(log.pdf14- What is Big-O notation- Give example algorithm for O(1)-O(n)-O(log.pdf
14- What is Big-O notation- Give example algorithm for O(1)-O(n)-O(log.pdfasser7
 
14-) Which of the following are valid variable names in Python- Give a.pdf
14-) Which of the following are valid variable names in Python- Give a.pdf14-) Which of the following are valid variable names in Python- Give a.pdf
14-) Which of the following are valid variable names in Python- Give a.pdfasser7
 
14-3- Give some examples of how technology is creating employer-employ.pdf
14-3- Give some examples of how technology is creating employer-employ.pdf14-3- Give some examples of how technology is creating employer-employ.pdf
14-3- Give some examples of how technology is creating employer-employ.pdfasser7
 
1-The substantia nigra resides within this brain region- 2-Complex spi.pdf
1-The substantia nigra resides within this brain region- 2-Complex spi.pdf1-The substantia nigra resides within this brain region- 2-Complex spi.pdf
1-The substantia nigra resides within this brain region- 2-Complex spi.pdfasser7
 
1-The substantia nigra resides within this brain region- 2-Complex sp.pdf
1-The substantia nigra resides within this brain region-  2-Complex sp.pdf1-The substantia nigra resides within this brain region-  2-Complex sp.pdf
1-The substantia nigra resides within this brain region- 2-Complex sp.pdfasser7
 
1- Which of the following will promote variation in a species- I- Meio.pdf
1- Which of the following will promote variation in a species- I- Meio.pdf1- Which of the following will promote variation in a species- I- Meio.pdf
1- Which of the following will promote variation in a species- I- Meio.pdfasser7
 
11- Use the simulator to create the entangled state 2101+2110-.pdf
11-  Use the  simulator to create the entangled state 2101+2110-.pdf11-  Use the  simulator to create the entangled state 2101+2110-.pdf
11- Use the simulator to create the entangled state 2101+2110-.pdfasser7
 
10- Two types of chemical bonding are shown in Figure 22- In the figur.pdf
10- Two types of chemical bonding are shown in Figure 22- In the figur.pdf10- Two types of chemical bonding are shown in Figure 22- In the figur.pdf
10- Two types of chemical bonding are shown in Figure 22- In the figur.pdfasser7
 
101051010.pdf
101051010.pdf101051010.pdf
101051010.pdfasser7
 
19- Ski Quarterly typically sells subscriptions on an annual basis- an.pdf
19- Ski Quarterly typically sells subscriptions on an annual basis- an.pdf19- Ski Quarterly typically sells subscriptions on an annual basis- an.pdf
19- Ski Quarterly typically sells subscriptions on an annual basis- an.pdfasser7
 
11- Daniel ordered 200 computer components from Muthu- Each component.pdf
11- Daniel ordered 200 computer components from Muthu- Each component.pdf11- Daniel ordered 200 computer components from Muthu- Each component.pdf
11- Daniel ordered 200 computer components from Muthu- Each component.pdfasser7
 

More from asser7 (20)

1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf
1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf
1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf
 
1-) What are the eight subfields of physical geography and what do the.pdf
1-) What are the eight subfields of physical geography and what do the.pdf1-) What are the eight subfields of physical geography and what do the.pdf
1-) What are the eight subfields of physical geography and what do the.pdf
 
1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf
1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf
1-)Review Exhibit 14-2- How could the concept of addressable TV advert.pdf
 
1-) What are the eight subfields of physical geography and what do the.pdf
1-) What are the eight subfields of physical geography and what do the.pdf1-) What are the eight subfields of physical geography and what do the.pdf
1-) What are the eight subfields of physical geography and what do the.pdf
 
1- Remember that enzymes (biological catalysts) are most often ______-.pdf
1- Remember that enzymes (biological catalysts) are most often ______-.pdf1- Remember that enzymes (biological catalysts) are most often ______-.pdf
1- Remember that enzymes (biological catalysts) are most often ______-.pdf
 
1- Pick any current Canadian political party of your choice (whether i.pdf
1- Pick any current Canadian political party of your choice (whether i.pdf1- Pick any current Canadian political party of your choice (whether i.pdf
1- Pick any current Canadian political party of your choice (whether i.pdf
 
1- Research Certificate based authentication techniques -& research On.pdf
1- Research Certificate based authentication techniques -& research On.pdf1- Research Certificate based authentication techniques -& research On.pdf
1- Research Certificate based authentication techniques -& research On.pdf
 
1- What is the history and evolution of government involvement in heal.pdf
1- What is the history and evolution of government involvement in heal.pdf1- What is the history and evolution of government involvement in heal.pdf
1- What is the history and evolution of government involvement in heal.pdf
 
1- What is the difference between a cell membrane and a cell wall- Des.pdf
1- What is the difference between a cell membrane and a cell wall- Des.pdf1- What is the difference between a cell membrane and a cell wall- Des.pdf
1- What is the difference between a cell membrane and a cell wall- Des.pdf
 
14- What is Big-O notation- Give example algorithm for O(1)-O(n)-O(log.pdf
14- What is Big-O notation- Give example algorithm for O(1)-O(n)-O(log.pdf14- What is Big-O notation- Give example algorithm for O(1)-O(n)-O(log.pdf
14- What is Big-O notation- Give example algorithm for O(1)-O(n)-O(log.pdf
 
14-) Which of the following are valid variable names in Python- Give a.pdf
14-) Which of the following are valid variable names in Python- Give a.pdf14-) Which of the following are valid variable names in Python- Give a.pdf
14-) Which of the following are valid variable names in Python- Give a.pdf
 
14-3- Give some examples of how technology is creating employer-employ.pdf
14-3- Give some examples of how technology is creating employer-employ.pdf14-3- Give some examples of how technology is creating employer-employ.pdf
14-3- Give some examples of how technology is creating employer-employ.pdf
 
1-The substantia nigra resides within this brain region- 2-Complex spi.pdf
1-The substantia nigra resides within this brain region- 2-Complex spi.pdf1-The substantia nigra resides within this brain region- 2-Complex spi.pdf
1-The substantia nigra resides within this brain region- 2-Complex spi.pdf
 
1-The substantia nigra resides within this brain region- 2-Complex sp.pdf
1-The substantia nigra resides within this brain region-  2-Complex sp.pdf1-The substantia nigra resides within this brain region-  2-Complex sp.pdf
1-The substantia nigra resides within this brain region- 2-Complex sp.pdf
 
1- Which of the following will promote variation in a species- I- Meio.pdf
1- Which of the following will promote variation in a species- I- Meio.pdf1- Which of the following will promote variation in a species- I- Meio.pdf
1- Which of the following will promote variation in a species- I- Meio.pdf
 
11- Use the simulator to create the entangled state 2101+2110-.pdf
11-  Use the  simulator to create the entangled state 2101+2110-.pdf11-  Use the  simulator to create the entangled state 2101+2110-.pdf
11- Use the simulator to create the entangled state 2101+2110-.pdf
 
10- Two types of chemical bonding are shown in Figure 22- In the figur.pdf
10- Two types of chemical bonding are shown in Figure 22- In the figur.pdf10- Two types of chemical bonding are shown in Figure 22- In the figur.pdf
10- Two types of chemical bonding are shown in Figure 22- In the figur.pdf
 
101051010.pdf
101051010.pdf101051010.pdf
101051010.pdf
 
19- Ski Quarterly typically sells subscriptions on an annual basis- an.pdf
19- Ski Quarterly typically sells subscriptions on an annual basis- an.pdf19- Ski Quarterly typically sells subscriptions on an annual basis- an.pdf
19- Ski Quarterly typically sells subscriptions on an annual basis- an.pdf
 
11- Daniel ordered 200 computer components from Muthu- Each component.pdf
11- Daniel ordered 200 computer components from Muthu- Each component.pdf11- Daniel ordered 200 computer components from Muthu- Each component.pdf
11- Daniel ordered 200 computer components from Muthu- Each component.pdf
 

Recently uploaded

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 

Recently uploaded (20)

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 

(C++)Why does this code shows a run time error - I would like some sug.docx

  • 1. (C++)Why does this code shows a run time error ? I would like some suggestions, and corrections.Thanks #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <iomanip> #include <array> #include <ctime> #include <limits> // <limits>:library used to define and access various properties of numerical // data types //(such as the maximum and minimum values) using namespace std; class Snack { private: string snackName; double priceSnack; int snackQuantity; int sold; string* transaction; string getCurrentTime() { time_t t = time(0); struct tm ts; char buff[10]; ts = *localtime(&t); strftime(buff, sizeof(buff), "%X", &ts); return buff; } public: Snack() { // Default constructor snackName = ""; priceSnack = 0; snackQuantity = 0; sold = 0; transaction = nullptr; } Snack(string name, double price, int quant)//Overload cosntructor { snackName = name; priceSnack = price; snackQuantity = quant; transaction = new string[quant];
  • 2. for (int i = 0; i < quant; i++) transaction[i] = ""; } // Creating accessor methods void setName(string s) { if (s.length() <= 0) { cout << "Please enter a name" << endl; } else snackName = s; } void setPrice(double pr) { if (pr <= 0) { cout << "Please enter a price greater than 0" << endl; } else priceSnack = pr; } void setQuantity(int qt) { if (qt <= 0) { cout << "Please enter number greater than 0" << endl; } else { snackQuantity = qt; transaction = new string[qt]; for (int i = 0; i < qt; i++) transaction[i] = ""; } } // Creatting getters string getName() const { return snackName; } int getInStock() const { return snackQuantity; } int getSold() const { return sold; } double getPrice() const { return priceSnack; }
  • 3. bool buyItem(double& moneyEntered) { if (snackQuantity == 0) { cout << "Error: item is sold-out" << endl; return false; } if (moneyEntered >= priceSnack) { moneyEntered -= priceSnack; transaction[sold] = getCurrentTime(); snackQuantity--; sold++; cout << "Item has been dispensed below" << endl; return true; } else if (moneyEntered < priceSnack) { if (moneyEntered < 0) { cout << "Please enter a number greater than 0" << endl; } else { cout << "Amount is less than the price $" << priceSnack << endl; } return false; } } ~Snack() // Destructor { if (sold) { cout << "nClosing details for " << snackName << "n"; cout << "ntNumber of sold: " << priceSnack; cout << "ntProfit Gained: " << priceSnack * snackQuantity << "nn"; for (int i = 0; i < sold; i++) { cout << "t" << transaction[i] << endl; } } delete[] transaction; transaction = nullptr; cout << endl; } }; void displayVendingMachine(const Snack[], const int); int getQuarters();
  • 4. void userBuyItem(Snack[], const int); bool promptToContinue(); int main() { const int SNACK_MAX = 3; Snack snack[SNACK_MAX] = { Snack(), Snack("Candy", 1.25,5), Snack("Soda",1.00,2) }; snack[0].setName("Chips"); snack[0].setPrice(1.75); snack[0].setQuantity(3); cout << "Welcome to the vender machine!nn"; do { userBuyItem(snack, SNACK_MAX); } while (promptToContinue()); } // Function for formatting void displayVendingMachine(const Snack snacks[], int size) { cout << "Welcome to the Snack Vending Machine!" << endl; cout << setw(54) << setfill('-') << "-" << setfill(' ') << endl; cout << setw(5) << "Item #" << setw(20) << "Item Name" << setw(13) << "Price" << setw(14) << "# in Stock" << endl; cout << setw(54) << setfill('-') << "-" << setfill(' ') << endl; for (int i = 0; i < size; i++) { cout << setw(5) << i + 1 << setw(20) << snacks[i].getName() << setw(10) << "$" << fixed << setprecision(2) << snacks[i].getPrice() << setw(10) << snacks[i].getInStock(); cout << endl; } cout << setw(54) << setfill('-') << "-" << setfill(' ') << endl; cout << endl; } // Function to validate the quarters int getQuarters() { int quarter; // Continuously prompt the user until they enter a valid input while (true) { cout << "Enter a number of quarters: "; cin >> quarter;
  • 5. // Check if the user entered an invalid input (not a positive integer) if (cin.fail() || quarter < 1) { cout << "Invalid input. Enter a positive integer value greater than or" << " equal to 1: n"; // Clear the error flags in the cin stream cin.clear(); // Ignore any remaining characters in the input buffer cin.ignore(numeric_limits<streamsize>::max(), 'n'); continue; } // If a valid input was entered, exit the loop break; } return quarter; } void userBuyItem(Snack snack[], const int size) { displayVendingMachine(snack,size); int quarter = getQuarters(); int userInput; double money; cout << "Amount entered: " << quarter * 0.25 << endl; money = quarter * 0.25; while (true) { cout << endl << "Enter a number between 1 and " << size << " to make your selection: "; cin >> userInput; if (cin.fail() || userInput < 1 || userInput > size) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), 'n'); cout << "Error: enter a number between 1 and " << size << ": "; continue; } break; } snack[userInput - 1].buyItem(money);
  • 6. if (money > 0) cout << "$" << money << " dispensedn"; } bool promptToContinue() { char choice; cout << endl << "Continue? (Y / N): "; cin >> choice; if (choice == 'Y' || choice == 'y') return true; return false; }