SlideShare une entreprise Scribd logo
1  sur  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;
}

Contenu connexe

Similaire à (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
 

Similaire à (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
 

Plus de 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
 

Plus de 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
 

Dernier

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
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
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
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
 
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
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
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
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
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
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 

Dernier (20)

HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
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
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
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
 
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)
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
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
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
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
 
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
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 

(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; }