Validating Input & If/Else If Problem

So I made a code that calculates how much a person must pay for gas depending on how many gallons they purchased and if they paid by cash or credit (credit was .10 cents more per gallon). For this first problem we assumed the user would not enter invalid input and make a copy of it. Now i have to edit it to include while-loops to validate the input from the user. Everything else applies, except now my program must let the user know when an invalid input is entered and should allow the user to re-enter a new value. Here's my code...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <iomanip>

using namespace std;

int main(){

        float gascash = 3.021;
        float gascredit = 3.121;
        double x, y;


	cout << "How many gallons of gas would you like to purchase?: " << endl;
        cin >> x;
        cout << "Are you paying with cash or credit? For cash, enter (1). For credit, enter (0): " << endl;
        cin >> y;
        if(y==1)
                cout << "Your total is: $" << setprecision(2) << fixed << gascash*x << endl;
        else if(y==0)
                cout << "Your total is: $" << setprecision(2) << fixed << gascredit*x << endl;

return 0;
}


Im very new to programming so any help is well appreciated! Thank you guys.
Something like this might be what you're looking for?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>
#include <Windows.h> // Allows access to the MessageBox function
#include <conio.h> // Allows access to the getch function
using namespace std;
int main ()
{
        float gascash = 3.021;
        float gascredit = 3.121;
        double x, y;
        while (1)
        {
			cout << "How many gallons of gas would you like to purchase?: " << endl;
			cin >> x;
			cout << "Are you paying with cash or credit? For cash, enter (1). For credit, enter (0): " << endl;
			cin >> y;
			if (y == 1) cout << "Your total is: $" << setprecision (2) << fixed << gascash*x << endl;
			else if (y == 0) cout << "Your total is: $" << setprecision (2) << fixed << gascredit*x << endl;
			else
			{
				MessageBox (NULL, "Invalid input!", NULL, MB_ICONWARNING); // Invalid input
				continue; // Reset the loop
			}
			getch (); // Wait for user to press a key
			cout << endl << endl << endl; // Print some new lines to make the program look better
        }
	return 0;
}
Last edited on
Topic archived. No new replies allowed.