Duncan
Duncan

Reputation: 819

Shopping Calculator

i need to create a program that adds prices to a running total and gives you your end total when you are ready to check out.

I wrote up a program that does the totaling fine but i think screwed up in my looping somewhere and it skips over certain instances of cin.get after you select that you don't want to check out.

I also want to incorporate "press q to quit" instead of "do you want to check out" but im working on that and dont expect issues.

any ideas on how i can fix my code so it doesnt skip past my input commands?

#include <iomanip>
#include <iostream>

using namespace std;
const int MAXCHAR = 101;

int main()
{
    double itemPrice = 0;
    double totalPrice = 0;
    char itemName[MAXCHAR];
    char confirm;
    char checkoutConfirm;
    char reply;
    bool checkout = false;


    while (checkout == false)
    {
        cout << "Enter Item Name(100 characters or less): ";
        cin.get(itemName, MAXCHAR, '\n');
        cin.ignore(100, '\n');

        cout << "Enter Item Price: ";
        cin >> itemPrice;
        while(!cin)
        {
            cin.clear();
            cin.ignore(100, '\n');
            cout << "Invalid Input. Enter Item Price: \n\n";
            cin >> itemPrice;
        }
        cout << "Your entry:" << endl;
        cout << itemName << " - $" << itemPrice << "\n";
        cout << "Correct?(y/n): ";
        cin >> confirm;

        if (confirm == 'y' || confirm == 'Y')
        {
            totalPrice += itemPrice;
            cout << "Your total is: " << totalPrice;
            cout << "Would you like to check out?(y/n): ";
            cin >> checkoutConfirm;
            if (checkoutConfirm == 'y' || checkoutConfirm == 'Y')
            checkout = true;
            else if (checkoutConfirm == 'n' || checkoutConfirm == 'N')
            checkout = false;
            else 
            {
                cout << "Invalid Input. Enter y to checkout or n to keep shopping: ";
                cin >> checkoutConfirm;
            }
        }
        else if (confirm == 'n' || confirm == 'N')
        {
            cout << "Entry deleted -- Enter new information: \n";
        }
        else 
        {
            cout << "Invalid Input. Enter y to checkout or n to keep shopping: ";
            cin >> confirm;
        }         
    }
    return 0;
}

Upvotes: 0

Views: 756

Answers (1)

0x8BADF00D
0x8BADF00D

Reputation: 972

Clear the input stream buffer before using it again:

std::cin >> x;
std::cin.ignore();
std::cin.clear();

http://www.cplusplus.com/reference/istream/istream/ignore/ http://www.cplusplus.com/reference/ios/ios/clear/

Otherwise your input may remain in the buffer and will be used again. As far as I can see, you already did that sometimes, though you forgot it quite often.

Additionally you may take a look into this question regarding your quit procedure.

Upvotes: 1

Related Questions