Need help exiting a while loop

Hello everyone, I am currently writing a code that is supposed to take the users miles driven and gallons used to produce the MPG. I have majority of the code done but for some reason when i use -1 to exit it still wants the user to enter in gallons used, if you could help me I'd appreciate it!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <conio.h>
using namespace std;

 int main()
 {
 	float miles;
	float gallons;
	float MPG;
	
	while(miles != -1)
	{
		cout << "Enter miles driven (-1 to quit): "; cin >> miles;
		cout << "Enter gallons used: "; cin >> gallons;
		
		MPG = miles / gallons;
		
		cout << "Total MPG: " << MPG << endl; 
	}
	
	return 0;
	getch();
}
Last edited on
Look where you input miles and gallons (those statements should be on lines by themselves, by the way). If you enter -1 for miles there's no "logic" to stop it from continuing on to ask you for the gallons, etc.

So you need an if statement after cin>>miles, something like:
1
2
3
4
5
6
7
8
9
10
11
12
while (miles >= 0)
{
    cout << "Enter miles driven (-1 to quit): ";
    cin >> miles;
    if (miles >= 0) // any negative value quits
    {
        cout << "Enter gallons used: ";
        cin >> gallons;
        MPG = miles / gallons;
        cout << "Total MPG: " << MPG << endl; 
    }
}


Your getch() is not going to do anything after the return 0! It should be before it. We also generally suggest that you not use conio.h (as it is not portable) and do something like this to hold the console open (due to a substandard IDE):
1
2
char ch;
cin >> ch;   // enter a non-whitespace character to end 


(And tabs suck. Space are better. 4 is standard.)
Last edited on
I see, thank you so much!
Topic archived. No new replies allowed.