c++ - Utilizing char to determine output isnt working -
i'm trying make when user inputs either r or p different portion execute reason it's not recognizing single character inputs. taking me first if statement saying don't have right value, executing r regardless of enter. why isn't working me? tried both letter , ascii number corresponding letters , each time same thing. not outputting final statement says invalid service code try again. program looks this. in advance time!
#include <iostream> #include <iomanip> #include <string> using namespace std; int main() { char servicetype; int account; double minutes; double initialcharge; double overcharge; double day; double night; double dayrate; double nightrate; double balance; string service; cout << "please enter account number: "; cin >> account; cout << endl; cout << "please enter service code: "; cin >> servicetype; cout << endl; if (servicetype != 'r' || 'r' || 'p' || 'p') { cout << "invalid service code entered. please enter valid service code of p premium service or r regular service: "; cin >> servicetype; cout << endl; } else if (servicetype == 'r' || 'r') { service = "regular"; initialcharge = 10.00; overcharge = .2; cout << "please enter number of minutes service used: "; cin >> minutes; cout << endl; balance = initialcharge + (minutes * overcharge); cout << "account number " << account << " " << service << " service utilized " << minutes << " minutes , therefore balance due of $" << fixed << setprecision(2) << balance << endl; } else if (servicetype == 'p' || 'p') { service = "premium"; initialcharge = 25.00; cout << "please enter number of minutes used between hours of 6:00 , 6:00 pm: "; cin >> day; cout << endl; cout << "please eneter number of minutes used between hours of 6:00 pm , 6:00 am: "; cin >> night; cout << endl; if (day < 75) dayrate = 0; else dayrate = (day - 75) * .1; if (night < 100) nightrate = 0; else nightrate = (night - 100) * .05; balance = initialcharge + nightrate + dayrate; minutes = day + night; cout << "account number " << account << " " << service << " service utilized " << minutes << " minutes , therefore balance due of $" << fixed << setprecision(2) << balance << endl; } else cout << "an invalid service code entered, please try again." << endl; system("pause"); return 0; }
you need compare servicetype
each letter. is, saying:
"if servicetype
not 'r' or if 'r' ... etc" evaluates true
always, because 'r'
(which gets converted number equivalent) evaluates true
. similar saying:
if ('r') { }
you can fix comparing servicetype
each character:
if (servicetype != 'r' && servicetype != 'r' && servicetype != 'p' && servicetype != 'p') { }
you simplify using tolower
(or toupper
):
if (tolower(servicetype) != 'r' && tolower(servicetype) != 'p') { }
Comments
Post a Comment