whenever I type correct choices, it still says INVALID, other letters should be invalid help please

here is the code:

#include<iostream>
using namespace std;

main()
{
char parking_lvl;
float parking_hrs,total,discount;

cout<<"Enter total hours: ";
cin>>parking_hrs;

cout<<"Enter parking level: ";
cin>>parking_lvl;

if(parking_lvl=='A'||parking_lvl=='a')
{
if(parking_hrs>2)
total=((parking_hrs-2)*30)+20;
else
total=30;
}

if(parking_lvl=='B'||parking_lvl=='b')
{
{
if(parking_hrs>2)
total=((parking_hrs-2)*30)+20;
else
total=30;
}
discount=total*0.05;
total=total-discount;
}

if(parking_lvl=='C'||parking_lvl=='c')
{
{
if(parking_hrs>2)
total=((parking_hrs-2)*30)+20;
else
total=30;
}
discount=total*0.10;
total=total-discount;
}

else
cout<<"invalid";

}
Last edited on
Your code will put invalid every time the entered parking level is not 'C' or 'c'. This is because the else-part of this statement only belongs to the last if, which checks if the parking level is 'C' or 'c'. You could make it belong to all statements by changing your if conditionals into else if (which would also exclude some unnecessary tests):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

if(parking_lvl == 'A' || parking_lvl == 'a')
{
    //Some code
}
else if(parking_lvl == 'B' || parking_lvl == 'b')
{
    //More code
}
else if(parking_lvl == 'C' || parking_lvl == 'c')
{
    //Even more code
}
else
    std::cout << "invalid";


This way, the else conditional will only be executed when the first three if's failed, not when only the last failed.
Topic archived. No new replies allowed.