# while loop problem

• 03-14-2005
chrismax2
while loop problem
Hey,

I find with all my programmes I write, if I have two inputs to enter, within the while loop, it wont end until the last input has been put in, in the past I went round it the long way by putting an 'if' statment in to break the loop after the first input, but what is the correct way to solve this problem, I had a quick look at the QA's and the Search thing, but not much luck
Code:

```         while (( miles != -1) || ( liters != -1 ))         {         cout << "Please enter number of miles you have driven or -1 to quit" << endl;         cin >> miles;         cout << "Please enter number of liters you put in your car to fill it up" << endl;         cin >> liters;         answer = compute(liters, miles);         cout << "You have travled " << answer << " miles per gallon" << endl;         }         return 0;```
Thanks, ps not homework as I am only teaching myself, in the UK I can never find any (cheap) lessions on C++ anyway.
• 03-14-2005
laserlight
Actually, since you state the part about entering -1 only at the prompt for miles, you'll only need to test miles.
So the loop condition becomes (miles != -1)

THe quirk with the way you do it might be that a user could enter -1 for miles, and then still be greeted with a prompt for liters.
An alternative to fix this might be to use an infinite loop, breaking out of it if miles is tested to be -1.
Code:

```//loop ends when miles == -1 for (;;) {         //prompt for miles, enter -1 to quit         cin >> miles;         if (miles == -1)                 break; //end loop here!         //prompt for liters         cin >> liters;         //compute answer         //print result }```
• 03-14-2005
hk_mp5kpdw
Code:

```cout << "Please enter number of miles you have driven or -1 to quit" << endl; cin >> miles; while ( miles != -1 ) {     cout << "Please enter number of liters you put in your car to fill it up" << endl;     cin >> liters;     answer = compute(liters, miles);     cout << "You have travled " << answer << " miles per gallon" << endl;     cout << "Please enter number of miles you have driven or -1 to quit" << endl;     cin >> miles; } return 0;```