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...
#include <iostream>
#include <iomanip>
usingnamespace 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;
elseif(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.
#include <iostream>
#include <iomanip>
#include <Windows.h> // Allows access to the MessageBox function
#include <conio.h> // Allows access to the getch function
usingnamespace 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;
elseif (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;
}