Repeat Program in Xcode - C++ - c++

The program is supposed to repeat after the user enters incorrect data for hours, minutes, seconds.
I can't get programs to loop on Xcode.
Example:
user enters invalid data for hours, minutes, and seconds.
Program displays "invalid data", and then asks the user if they would like to repeat the program, if the user enters "y or Y", the program asks the user to enter the time again.
#include <iostream>
#include <iomanip>
using namespace std;
struct Time
{
int hours ;
int seconds;
int minutes;
};
void getTime(Time &time);
bool isTimeValid(Time &time);
void addOneSecond(Time &time);
void displayTime(Time &time);
const int MAX_HOURS = 23;
const int MAX_MINS = 59;
const int MAX_SECS = 59;
int main()
{
Time time;
getTime(time);
isTimeValid(time);
addOneSecond(time);
displayTime(time);
return 0;
}
void getTime(Time &time)
{
cout << "Enter the time in \"military time\", (24-hour format), in"
<< " the following order:\nHH:MM:SS, (Hours, Minutes, Seconds).\n\n";
cout << "Hours: ";
cin >> time.hours;
cout << "Minutes: ";
cin >> time.minutes;
cout << "Seconds: ";
cin >> time.seconds;
cout << endl << endl;
}
bool isTimeValid(Time &time)
{
bool answer = ' ';
if (((time.hours >= 0) && (time.hours <= MAX_HOURS)) &&
((time.minutes >= 0) && (time.minutes <= MAX_MINS)) &&
((time.seconds >= 0) && (time.seconds <= MAX_SECS)))
{
return true;
}
else
{
cout << "Invalid Time.\n\n";
return false;
}
cout << "Do it again? (Y/N)";
cin >> answer;
do
{
getTime(time);
isTimeValid(time);
addOneSecond(time);
displayTime(time);
} while(toupper(answer) == 'T' );
}
void addOneSecond(Time &time)
{
time.seconds++;
if (time.seconds > MAX_SECS)
{
time.seconds = 0;
time.minutes++;
}
}
void displayTime(Time &time)
{
cout.fill('0');
cout << "After adding one second, the time is " << setw(2) << time.hours
<< ":" << setw(2) << time.minutes << ":" << setw(2)
<< time.seconds << ".\n\n";
}

Related

My if statements inside my while loop keep repeating forever when they are not suppose to be. It should go back to the while loop after the if stateme

So im working on a project for school and i just cant get this to work. everything else seems to run but when i input the users choice for q, s, z10, z25,z5,z1 it loops indefinetly. i cant figure out why it keeps running the function over and over. im not quite sure if im just typing something wrong or what but this is the only thing im really stuck on currently. Here is the code
#include<iostream>
#include<string>
using namespace std;
struct Inventory
{
int Pack_25oz;
int Pack_10oz;
int Pack_5oz;
int Pack_1oz;
};
void show_Menu();
void initialize (Inventory& I);
void add_25OZ (Inventory& I, int P25);
void add_10OZ (Inventory& I, int P10);
void add_5OZ (Inventory& I, int P5);
void add_1OZ (Inventory& I, int P1);
void Place_Order(Inventory& I, int amount);
void show (Inventory& I);
int main(){
Inventory I;
string choice;
int nop= 0;
initialize(I);
show_Menu();
cout << "Dear User! please make a choice from above menu : " << endl;
getline(cin,choice);
while(choice!="q" or choice != "Q"){
if(choice == "s"|| choice == "S"){
show(I);
}
else if(choice == "z25" || choice == "Z25"){
cout << "Enter the number of packages : \n";
cin >> nop;
add_25OZ(I, nop);
}
else if(choice == "z10" || choice == "Z10"){
cout << "Enter the number of packages : \n";
cin >> nop;
add_10OZ(I, nop);
}
else if(choice == "z5"||choice == "Z5"){
cout << "Enter the number of packages : \n";
cin >> nop;
add_5OZ(I, nop);
}
else if(choice == "z1"|| choice == "Z1"){ // choice equal to "z1" or "Z1"
cout << "Enter the number of packages : \n" ; // prompt for number of packages
cin >> nop ; // accept user input
add_1OZ( I, nop);// call add_1OZ function
}
else if(choice == "o"||choice == "O") {
cout << "Enter the number of ounces : ";// prompt for number of ounces
int noun; // noun stands for number of ounces
cin >> noun;// accept user input
Place_Order( I, noun);
}
else if (choice == "q" || choice == "Q"){ // Output final message that the program has ended
cout << "The program has ended.";
break;
}
else
cout << "invalid comand" << endl;
};
return 0;
}
void show_Menu(){
cout << "S - Show Inventory" << endl;
cout << "Z25 - Add 25 oz packages"<< endl;
cout << "Z10 - Add 10 oz packages"<< endl;
cout << "Z5 - Add 5 oz packages"<< endl;
cout << "Z1 - Add 1 oz packages "<< endl;
cout << "O - Place order"<< endl;
cout << "Q - End"<< endl;
}
void show (Inventory& I)
{
cout << "The Inventory comprises of the following:\n 1. Pack_25oz : " << I.Pack_25oz << "\n 2.
Pack_10oz : " << I.Pack_10oz << "\n 3. Pack_5oz : " << I.Pack_5oz << "\n 4. Pack_1oz : " <<
I.Pack_1oz <<endl ;
}
void initialize (Inventory& I) {
int var = 0 ;
I.Pack_25oz = var;
I.Pack_10oz = var;
I.Pack_5oz = var;
I.Pack_1oz = var;
}
void add_25OZ (Inventory& I, int P25) {
I.Pack_25oz += P25;
}
void add_10OZ (Inventory& I, int P10) {
I.Pack_10oz += P10;
}
void add_5OZ (Inventory& I, int P5) {
I.Pack_5oz += P5;
}
void add_1OZ (Inventory& I, int P1) {
I.Pack_1oz += P1;
}
void Place_Order(Inventory& I, int amount) {
int subtract;
subtract = amount / 25;
if (I.Pack_25oz <= 0) {
cout << "Not enough packs" << endl;
} else { I.Pack_25oz -= subtract; }
amount = amount % 25;
subtract = amount / 10;
if (I.Pack_10oz <= 0) {
cout << "Not enough packs" << endl;
} else { I.Pack_10oz -= subtract; }
amount = amount % 10;
subtract = amount / 5;
if (I.Pack_5oz <= 0) {
cout << "Not enough packs" << endl;
} else { I.Pack_5oz -= subtract; }
amount = amount % 5;
subtract = amount / 1;
if (I.Pack_1oz <= 0) {
cout << "Not enough packs" << endl;
} else { I.Pack_1oz -= subtract;
cout << "Order Fufilled" << endl;
}
}
It seems you call getline outside of the loop. so choice is never updated.

I am having an issue with my program. It wants to keep skipping my second cin lines in visual studio and I don't know what the problem is

First, let me get this out of the way. I know my program is a little rough right now, but I can't even get to fixing it if lines 42-52 (future time input) are being skipped. So, for context, I need to make a time machine that can go forward 24 hours, and I need to make sure that the input for the start and future time is in the HH:MM xm format. Then I need to have the total minute difference, which can convert to the hours and minutes until the future time. Sorry if what I've done gives you a headache still learning.
Here is my code:
#include <iostream>
// Total number of minutes in an hour and day
const int MINUTES_IN_HOUR = 60;
const int MINUTES_IN_DAY = 24 * MINUTES_IN_HOUR;
// Function that computes the difference between two times
int convertDifference(int startHoursPar, int startMinutsPar, bool startIsAMPar, int endHoursPar, int endMinutesPar, bool endIsAMPar);
int main()
{
using namespace std;
int startHours;
int startMinutes;
bool startIsAM;
int endHours;
int endMinutes;
bool endIsAM;
char amPmChar;
char extra; //IMPORTANT!!
char answer;
int diff;
do
{
cout << "Enter start time, in the format 'HH:MM xm', where xm is \n" << "either 'am' or 'pm' for AM or PM: ";
cin >> startHours >> extra >> startMinutes >> startIsAM;
if (startIsAM == 'a' || startIsAM == 'A')
{
startIsAM = true;
}
else
{
startIsAM = false;
}
cout << "\nEnter future time, in the format 'HH:MM xm', where xm is\n" << "either 'am' or 'pm' for AM or PM: ";
cin >> endHours >> extra >> endMinutes >> endIsAM;
if (endIsAM == 'a' || endIsAM == 'A')
{
endIsAM = true;
}
else
{
endIsAM = false;
}
diff = convertDifference(startHours, startMinutes, startIsAM, endHours, endMinutes, endIsAM);
/*if ((hours > 1) && (minutes > 1))
{
cout << "There are " << diff << " minuets " << "(" << hours << " hours and " << minutes << " minutes) between " << startHours << ":" << startMinutes << " and " << endHours << ":" << endMinutes << ".";
}
else
{
cout << "There are " << diff << " minuets " << "(" << hours << " hour and " << minutes << " minute) between " << startHours << ":" << startMinutes << " and " << endHours << ":" << endMinutes << ".";
}
*/
cout << endl << "\nRun again? (y / n): ";
cin >> answer;
} while (answer == 'y');
return 0;
}
int convertDifference(int startHoursPar, int startMinutsPar, bool startIsAMPar, int endHoursPar, int endMinutesPar, bool endIsAMPar)
{
int diff, hours, minutes, minutes2;
if (startIsAMPar == 'p')
{
if (startHoursPar >= 1 && startHoursPar < 12)
{
startHoursPar += 12;
}
}
if (endIsAMPar == 'p')
{
if ((startHoursPar >= 1) && (endHoursPar < 12))
{
endHoursPar += 12;
}
}
minutes = (startHoursPar * 60) + startMinutsPar;
minutes2 = (endHoursPar * 60) + endMinutesPar;
if ((startHoursPar >= endHoursPar) || ((startHoursPar == endHoursPar) && (startMinutsPar > endMinutesPar)))
{
endMinutesPar += MINUTES_IN_DAY;
}
diff = endMinutesPar - startMinutsPar;
if (diff > MINUTES_IN_DAY)
{
diff -= MINUTES_IN_DAY;
}
return diff;
}

FOR LOOP fails to iterate through the object vector where purchase transactions are stored

I'm unsure why when more than one transaction has been made the FOR LOOP won't iterate through the vector of "buyers". Am I missing something simple? I've spent the last few hours trying to fix this but to no avail. If any one could possibly help with my problem I'd be eternally grateful.
#include <iostream>
#include <iomanip>
#include <vector>
#include <cctype>
using namespace std;
//This class is for the car details that the user can purchase.
class cCar {
private:
string _sName;
double _dPrice;
public:
cCar(string s, double d)
{
_sName = s;
_dPrice = d;
}
string getName() { return _sName; }
double getPrice() { return _dPrice; }
};
//This is where all the car detail purchases are created and stored in the object 'carlist'
vector<cCar> CarDatabase(vector<cCar>& car_list)
{
car_list.push_back(cCar("Blue Nissan Skyline", 1000));
car_list.push_back(cCar("Red Mini", 3000));
car_list.push_back(cCar("Black Land Rover", 4000));
car_list.push_back(cCar("Beatle", 9000));
car_list.push_back(cCar("Ferrari", 300000));
return car_list;
}
//This class stores the user's transactions
class Finance {
private:
string _sUserName;
double _dCostOfCar;
string _sChosenCar;
int _iFinancePlan;
double _dDepositedAmount;
double _dMonthlyPayments;
double _dTotalLeftToPay;
public:
Finance(string sName, double dCostOfCar, string sChosenCar, int iFinancePlan, double dDepositedAmount, double dDMonthlyPayments, double dTotalLeftToPay)
{
_sUserName = sName;
_dCostOfCar = dCostOfCar;
_sChosenCar = sChosenCar;
_iFinancePlan = iFinancePlan;
_dDepositedAmount = dDepositedAmount;
_dMonthlyPayments = dDMonthlyPayments;
_dTotalLeftToPay = dTotalLeftToPay;
}
string getUserName() { return _sUserName; }
double getdCostOfCar() { return _dCostOfCar; }
string getChosenCar() { return _sChosenCar; }
int getFinancePlan() { return _iFinancePlan; }
double getDepositAmount() { return _dDepositedAmount; }
double getMonthlyAmount() { return _dMonthlyPayments; }
double getTotalLeftToPay() { return _dTotalLeftToPay; }
};
//1. This displays the car menu items.
void display_menu(vector<cCar>& car_list)
{
cout << "\nMENU";
for (int iCount = 0; iCount != car_list.size(); iCount++) {
cout << "\n" << iCount + 1 << ". " << car_list[iCount].getName();
cout << "\n\tPrice: £" << car_list[iCount].getPrice();
cout << "\n";
}
}
//This procedure proccesses the user's selection and all information regarding price and name of car are then transferred to transaction variables.
void selectedCar(vector<cCar>& car_list, string& sNameOfChosenCar, double& dCostOfChosenCar)
{
int iSelectionFromMenu = -1;
do {
cout << "\nChoose a car that you'd wish to buy from the menu (1 - " << car_list.size() << "): ";
cin >> iSelectionFromMenu;
if (iSelectionFromMenu > 0 && iSelectionFromMenu <= car_list.size()) {
sNameOfChosenCar = car_list[iSelectionFromMenu - 1].getName();
dCostOfChosenCar = car_list[iSelectionFromMenu - 1].getPrice();
}
else {
cout << "\nPlease enter valid number!";
iSelectionFromMenu = -1;
}
} while (iSelectionFromMenu == -1);
}
//This procedure gets from the user their preferred finance plan through their input.
void FinanceLength(int& iFinanceLength)
{
do {
cout << "\nHow long do you wish for your finance plan to last? (1 - 4 years): ";
cin >> iFinanceLength;
if (iFinanceLength < 0 || iFinanceLength > 4) {
cout << "\nOops, try again! Please enter between 1 - 4!";
}
} while (iFinanceLength < 0 || iFinanceLength > 4);
}
//This procedure gets the user's deposit.
void DepositMoney(double& dDepositAmount)
{
do {
cout << "\nEnter deposit amount (minimum £500 accepted): £";
cin >> dDepositAmount;
if (dDepositAmount < 500) {
cout << "\nTry again! Deposit an amount greater than or equal to £500.";
}
} while (dDepositAmount < 500);
}
//This function calculates the amount of money the user has to pay after deposit, added tax and charge percentage of 10%
double TotalLeftToPay(double iFinanceLength, double dDepositAmount, double dCostOfChosenCar)
{
double dChargePercentage = 0.10;
double dTotalLeftToPay = dCostOfChosenCar + (dCostOfChosenCar * dChargePercentage) - dDepositAmount + 135;
return dTotalLeftToPay;
}
//This calculates monthly payments.
double MonthlyPayments(double dTotalLeftToPay, int iFinanceLength)
{
double dMonthlyPayments = (dTotalLeftToPay / iFinanceLength) / 12;
return dMonthlyPayments;
}
//This asks the user whether they'd like to restart the application.
void RestartOptions(char& cOption, bool& bExit)
{
do {
cout << "\nDo you wish to make another purchase? (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
switch (cOption) {
case 'Y':
bExit = false;
break;
case 'N':
bExit = true;
break;
default:
cout << "Sorry, that's an invalid input, please try again!";
continue;
}
} while (cOption != 'y' && cOption != 'Y' && cOption != 'n' && cOption != 'N');
}
//This string function returns either year or years (plural)
string YearOrYears(int iFinanceLength)
{
return (iFinanceLength > 1) ? "years" : "year";
}
//This displays receipt of the user's transaction.
//HERE IS WHRERE I "M STRUGGLING TO ITERATE
void Receipt(const string& sUserName, const int& iFinanceLength, const double& dDepositAmount, char cOption, bool& bExit, const string& sNameOfChosenCar, const double& dCostOfChosenCar, vector<Finance>& buyers)
{
double dTotalLeftToPay = TotalLeftToPay(iFinanceLength, dDepositAmount, dCostOfChosenCar);
double dMonthlyPayments = MonthlyPayments(dTotalLeftToPay, iFinanceLength);
buyers.push_back(Finance(sUserName, dCostOfChosenCar, sNameOfChosenCar, iFinanceLength, dDepositAmount, dMonthlyPayments, dTotalLeftToPay));
for (int iCount = 0; iCount != buyers.size(); iCount++) {
cout << "\nReceipt for: " << buyers[iCount].getUserName() << ". ";
cout << "\nYou have chosen " << buyers[iCount].getChosenCar() << ".";
cout << "\nYour finance plan timescale is " << buyers[iCount].getFinancePlan() << " " << YearOrYears(iFinanceLength) << ".";
cout << "\nYou've deposited £" << buyers[iCount].getDepositAmount() << ".";
cout << "\nTotal left to pay: £" << buyers[iCount].getTotalLeftToPay();
cout << "\nMonthly Payments: £" << buyers[iCount].getMonthlyAmount();
cout << "\n";
}
RestartOptions(cOption, bExit);
}
//This asks the user whether they're happy with the options of they've chosen.
void AcceptDeclineOptions(string& sUserName, int& iFinanceLength, double& dDepositAmount, bool& bExit, string& sNameOfChosenCar, double& dCostOfChosenCar, vector<Finance> buyers)
{
char cOption = 0;
do {
cout << "\nConfirm finance plan (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
if (cOption == 'Y' || cOption == 'N') {
if (cOption == 'Y') {
Receipt(sUserName, iFinanceLength, dDepositAmount, cOption, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
}
else {
RestartOptions(cOption, bExit);
}
}
else {
cout << "\nSorry, that's not a valid command.";
}
} while (cOption != 'Y' && cOption != 'N');
}
int main()
{
bool bExit = false;
int iFinanceLength = 0;
double dDepositAmount = 0;
string sNameOfChosenCar = "";
double dCostOfChosenCar = 0;
vector<cCar> car_list;
CarDatabase(car_list);
vector<cCar> car_purchases;
vector<Finance> buyers;
do {
cout << "Welcome!";
string sUserName = "";
cout << "\nEnter your name: ";
cin >> sUserName;
display_menu(car_list);
selectedCar(car_list, sNameOfChosenCar, dCostOfChosenCar);
FinanceLength(iFinanceLength);
DepositMoney(dDepositAmount);
AcceptDeclineOptions(sUserName, iFinanceLength, dDepositAmount, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
} while (bExit == false);
}

What should I change or delete in order to fix this code so the rest may work fine?

#include <h1>iostream <h2>
#include <h1>cmath<h2>// for + of months, days, and years
#include <h1>fstream<h2> //for in and output
#include <h1>cstdlib<h2>
#include <h1>string<h2>//for string type
using namespace std;
class Device {//Input and store Device Description and Serial Numbers
protected:
string serial_number;
string device_description;
public:
Device() {
serial_number = ("6DCMQ32");
device_description = ("TheDell");
}
Device(string s, string d) {
serial_number = s;
device_description = d;
}
};
class Test {
protected:
string Test_Description;
static int recent_month, recent_day, recent_year, new_month;
static int nmonth, next_month, next_day, next_year, max_day;
public:
static void getMonth() {//Calculates the next/new month
next_month = recent_month + nmonth;
new_month = next_month % 12;
if (next_month >= 12) {
cout << "The next Date: " << new_month << " / ";
}
else {
cout << "The next Date: " << next_month << " / ";
}
}
static void getDay() { //Calculates day of next month
if (new_month == 4 || new_month == 6 || new_month == 9 || new_month == 11) {
max_day = 30;
}
else if (new_month == 2) {
max_day = 29;
}
else {
max_day = 31;
}
if (recent_day > max_day) {
cout << max_day << " / ";
}
else {
cout << recent_day << " / ";
}
}
static void getYear() {//Calculates the year of the next number of months
next_year = recent_year + next_month;
if (next_year >= 12) {
cout << recent_year + (next_month / 12) << endl;
}
else {
cout << next_year << endl;
}
}
static void getDate() {
Test::getMonth(), Test::getDay(), Test::getYear();
}
};
int Test::recent_month, Test::recent_day, Test::recent_year,
Test::new_month;
int Test::nmonth, Test::next_month, Test::next_day, Test::next_year,
Test::max_day;
class Lab : public Device, public Test {//Class Lab is a Child of Class Test and Class Device
protected:
static int n;
public:
friend istream & operator>>(istream & cin, const Lab & lab) {
cout << "Enter Device Description and serial number: ";
getline(cin, lab.device_description);//This is where the error is
getline(cin, lab.serial_number);//This is where the error is
cout << "Enter Test Description: ";
getline(cin, lab.Test_Description);//This is where the error is
cout << "Enter number of months: ";
cin >> lab.nmonth;
cout << "Enter the most recent date(mm/dd/yyyy): ";
cin >> lab.recent_month >> lab.recent_day >> lab.recent_year;
return cin;
}
friend ostream & operator<<(ostream & cout, const Lab & lab) {
cout << lab.device_description << " ";
cout << lab.serial_number << endl;
cout << lab.Test_Description << endl;
getDate();
return cout;
}
static void getFile() {
cout << "Enter the number of devices: ";
cin >> n;
Lab *obj = new Lab[n];
if (obj == 0) {
cout << "Memory Error";
exit(1);
}
for (int i = 0; i<n; i++) {
cin >> obj[i];
}
ofstream myfile("Device.dat", ios::binary);
myfile.write((char *)obj, n * sizeof(Lab));
Lab *obj2 = new Lab[n];
ifstream file2("Device.dat", ios::binary);
if (obj2 == 0) {
cout << "Memory Error";
exit(1);
}
file2.read((char *)obj2, n * sizeof(Lab));
for (int i = 0; i < n; i++) {
cout << obj2[i];
cout << endl;
}
delete[] obj2;
}
void getSearch(){
}
};
void main() {
Lab L;
L.getFile();
system("pause");
}
//Error C2665 'std::getline': none of the 2 overloads could convert all
the argument types
/*
Purpose: is to enter the number of months for the next test date of device with input of serial number, Device Description, Test Description, recent date, and the number of months of two tests. At the end the program must be searched by having the user to input the serial number and the next date, if these two are valid everything in the device is listed out.
*/<
You shouldn't name your parameters like objects of the standard library (cin).
For an argument to be modifiable it must not be a reference to a constant entity.
Also, a std::istream bound operator<<() overload should not do output, but only extract the object required from the stream.

Uninitialized variable being used

I have this code here that works pretty decent except for when we get down to the 'processData' function where I receive the error
"The variable 'totalPay' is being used without being initialized."
I've been working on this for a couple hours and my brain is going numb, any help would be appreciated.
#include <iostream>
#include <string>
#include <climits>
#include <iomanip>
using namespace std;
// Prototypes
int readInt(string errorMsg = "", int min = INT_MIN, int max = INT_MAX);
void getData(string&, int&, char&, double&);
char getChoice(string prompt, char char1, char char2);
double processData(char service);
void display(string, int, char, double);
// Regular service
const double RCHARGE = 10.00; // Regular service base rate for first REG_MINS.
const double RPERMIN = 0.20; // Regular service cost per minute over REG_MINUTES.
const int REG_MINS = 50; // Regular service free minutes.
// Premium service
const double PCHARGE = 25.00; // Minimum charge for premium service.
const double P_PER_MIN_DAY = 0.10; // Charge per day minutes after 75.
const double P_PER_MIN_NIGHT = 0.05; // Charge per night minutes after 100.
const int P_DAY = 75; // Number of free minutes allowed during the day.
const int P_NIGHT = 100; // Number of free minutes allowed during the night.
int main()
{
string name; // Stores the users name.
int accountNumber; // Stores the users account number.
char serviceType; // Stores the users service type.
double minutes; // Stores the users minutes.
double totalPay; // Recieves the total pay from processData.
bool loopies = true;// Controls the loop while condition is true.
while (loopies == true)
{
getData(name, accountNumber, serviceType, minutes);
totalPay = processData(serviceType);
display(name, accountNumber, serviceType, totalPay);
}
return 0;
}
// Checks ints to make sure they are valid.
int readInt(string errorMsg, int min, int max)
{
int someInt;
bool valid = false;
do
{
// User entering account number
cin >> someInt;
// Verifying the data is valid (0 to 9999)
valid = (someInt >= min && someInt <= max);
// Clearing out invalid data and prompting for re-entry
if (cin.fail() || !valid || !isspace(cin.peek()))
{
cout << "Error! Invalid input." << endl;
cout << errorMsg << " must be whole number between " << min << " and " << max << endl;
cout << "Try Again: ";
cin.clear(); // Clearing the fail state
cin.ignore(numeric_limits<streamsize>::max(), '\n');
valid = false;
}
} while (!valid);
// Clears out following incorrect data once correct
cin.ignore(100, '\n');
return someInt;
}
// Takes all user data and checks input.
void getData(string &name, int &account, char &service, double &bill)
{
cout << "Enter customer name or \"Exit\" to end program: ";
getline(cin, name);
if (name == "Exit" || name == "EXIT" || name == "exit")
{
cout << "Program closing..." << endl;
system("pause");
exit(EXIT_SUCCESS);
}
cout << "Enter account number: ";
account = readInt("Account", 0, 10000);
cout << "Enter service type (R for regular or P for premium): ";
service = getChoice("Service", 'r', 'p' );
}
char getChoice(string input, char char1, char char2)
{
char character; // Stores the users character.
bool valid = false; // Controls the loop.
do
{
cin >> character;
character = tolower(character);
valid = (character == char1 || character == char2);
if (!valid || !isspace(cin.peek())) {
cout << "Invalid input!" << endl;
cout << input << " needs to be " << char1 << " or " << char2 << endl;
cout << "Try again: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
valid = false;
}
} while (!valid);
cin.ignore(100, '\n');
return toupper(character);
}
double processData(char service)
{
int dayMin; // Stores the users day minutes.
int nightMin; // Stores the users night minutes.
double totalPay; // Stores the total pay.
double dayPay; // Stores the pay for day minutes.
double nightPay; // Stores the pay for night minutes.
if (service == 'r')
{
cout << "Enter minutes used: ";
cin >> dayMin;
dayMin = readInt("Minutes ", 0, INT_MAX);
if (dayMin > REG_MINS)
{
dayMin -= REG_MINS;
totalPay = (dayMin * RPERMIN) + RCHARGE;
}
else
{
totalPay = RCHARGE;
}
totalPay = nightPay + dayPay - RCHARGE;
}
else if (service == 'p')
{
cout << "Enter day minutes: ";
cin >> dayMin;
dayMin = readInt("Minutes ", 0, INT_MAX);
if (dayMin > P_DAY)
{
dayMin -= P_DAY;
dayPay = (dayMin * P_PER_MIN_DAY) + PCHARGE;
}
else
{
dayPay = PCHARGE;
}
cout << "Enter night minutes: ";
cin >> nightMin;
nightMin = readInt("Minutes ", 0, INT_MAX);
if (nightMin > P_NIGHT)
{
nightMin -= P_NIGHT;
nightPay = (nightMin * P_PER_MIN_NIGHT) + PCHARGE;
}
else
{
nightPay = PCHARGE;
}
}
return totalPay;
}
void display(string name, int account, char service, double bill)
{
string switchService;
switch (service)
{
case 'R':
switchService = "Regular";
break;
case 'P':
switchService = "Premium";
break;
default:
cout << "Invalid character.";
}
cout << fixed << setprecision(2);
cout << endl;
cout << "Customer Name: " << name << endl;
cout << "Account number: " << account << endl;
cout << "Service type: " << switchService << endl;
cout << "Amount due: $" << bill << endl << endl;
}
In processData(), if service is neither p nor r, totalPay is never assigned before returning.
You may initialize it on declaration like
double totalPay = 0.0;