**This is an old revision of the document!**


Cougar Cash with input validation and user confirmation

Problem Statement

  • Everyday you go to the BYU Candy Counter and buy chocolate covered cinnamon bears using your Cougar Cash card.
  • Write a program which prompts the user how much they want to spend on candy, and then prints out the card balance and what cash is still owed.
  • The initial card balance is$10.00.
  • Any purchase greater than what is on the card should use up the balance on the card.

Additions from Cougar Cash

  • Check whether the input from the user is a valid amount. If not, prompt the user again.
  • If the desired expense is more than what is on the card, you prompt the user before charging the expense to the card.

Solution

#include <iostream>
#include <iomanip>
#include <string>
 
using namespace std;
 
const double INITIAL_BALANCE = 10.00;
 
int main()
{
	// inputs: how much they want to spend
	// outputs: balance after purchase, cash owed
	cout << fixed << setprecision(2);
 
	// Prompt the user
	double desired_expenditure;
	double balance = INITIAL_BALANCE;
 
	cout << "How much you wanna spend on bears? $";
	cin >> desired_expenditure;
 
	// Check that input is positive
	if (desired_expenditure < 0)
	{
		cout << "You can't buy $" << desired_expenditure << 
			" of bears!! Silly! Try again: $";
		cin >> desired_expenditure;
	}
 
	// if input > balance
	if (desired_expenditure > balance)
	{
		// Check if they wanna use the card still
		cout << "That's more than is on the card. Still wanna use the card? (Y/N) ";
		string input;
		cin >> input;
 
		if (input == "Y")
		{
			// report (input - balance) as still owed
			cout << "$" << (desired_expenditure - balance) << " is still owed" << endl;
			// update balance to 0
			balance = 0;
		}
		else
		{
			return 0; // or -1 if this is considered an erroneous transaction
		}
 
	}
	// otherwise
	else
	{
		// balance = balance - input
		balance -= desired_expenditure;
	}
 
	// DOESN"T WORK, can't reference input
	// cout << "Your input way back there was " << input;
 
	// print balance
	cout << "Your new balance is $" << balance << endl;
 
	system("pause");
	return 0;
}
cs-142/cougar-cash-with-input-validation-and-user-confirmation.1431377600.txt.gz · Last modified: 2015/05/11 14:53 by cs142ta
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0