do while statement

Simple issue: Not able to figure out why the do portion is looping even if the response is any character other than Y or y.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//BMI Calculator using user input
//Created by Ashish Mishra
//Oct 1st, 2011

#include<iostream>
#include<iomanip>
#include<math.h> // avoid cmath due to ambugious error

using namespace std;

int main()
{
    unsigned int weight;
    unsigned int height;
    float bmi;
    char response;
    
    do 
    {
    cout<<"*****************************\n";
    cout<<"Please enter your weight (lbs): ";
    cin>>weight;
    cout<<"Please enter your height (inches): ";
    cin>>height;
    bmi = (weight/pow(height,2))*703;
    cout<<"\n";
    cout<<fixed<<showpoint<<setprecision(2);
    cout<<"Your BMI is "<<bmi<<endl;
    
    if (bmi < 18.5)
       {  // braces used to illustrate use of compound statement.
       cout<<"You are underweight!"<<endl;
       cout<<"Eat more!!"<<endl;
       }
       else if (bmi >= 18.5 && bmi <25)   
       cout<<"You are normal!"<<endl;
       else if (bmi >= 25 )
       cout<<"You are overweight!"<<endl;
       else
       cin.get();
    
       cin.get();
       cout<<endl;
       
       cout<<"Would you like to enter the information again? ";
       cin>>response;
    }
    while (response == 'Y' || 'y' );
    
return 0;
    
}
while (response == 'Y' || 'y' );

This says:

while one of the following two things is true -
1) response equals 'Y'
2) 'y'

Note that point two is not "response equals 'y' "

So, sometimes point one will come up as true, sometimes it will be false.
Point 2 will always, always be true. 'y' is not zero, and thus is true. Always.

I suspect you meant this to be

while one of the following two things is true -
1) response equals 'Y'
2) response equals 'y'

which can be coded as

while (response == 'Y' || response == 'y' );
Thank you. It was an easy fix. :)
Topic archived. No new replies allowed.