Why does my "while" loop execute no matter what i enter? - c++

/*********************************************************
** Purpose: Asks the user for cable package they bought **
** and the amount of hrs they used and //tells them **
** their monthly bill **
**********************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Defining variables
double hours_over; //Amount of hrs the user went over their monthly allottment
double extra_pay; //Extra bill amount for going over monthly hrs allotted
double monthly_bill; //Monthly bill the user will pay
int hours; // How many hours the user used during the month
char package; //The package the user chose
//Getting the package the user bought
cout << "Your monthly subscription bill is based on your package.";
cout << "\n\nWhat package did you buy? Enter A, B or C: ";
cin >> package;
//Validating user input-must enter A, B or C
while (package != 'A' || package != 'B' || package != 'C')
{
cout << "\nPlease enter A, B or C(capitalized).";
cout << "\n\nWhat package did you buy?: ";
cin >> package;
}
//Getting hours the user used during month
cout << "How many hours did you use?: ";
cin >> hours;
//Validating user input-hrs cant exceed 744
while (hours > 744)
{
cout << "I'm sorry but your monthly usage cannot exceed 744 hrs.";
cout << "\nPlease enter another number.";
cout << "How many hours did you use?: ";
cin >> hours;
}
//Fixing decimal place of answers
cout << setprecision(2) << fixed << showpoint << endl;
//Switch statement-go to the package the user bought
switch (package)
{
case 'A':
if (hours > 10)
{
hours_over=hours-10;
extra_pay=hours_over*(2.00);
monthly_bill=9.95+extra_pay;
cout << "Your monthly bill is: $" << monthly_bill << endl;
}
else
{
cout << "Your monthly bill is: $9.95";
}
break;
case 'B':
if (hours > 20)
{
hours_over=hours-20;
extra_pay=hours_over;
monthly_bill=14.95+extra_pay;
cout << "Your monthly bill is: $" << monthly_bill << endl;
}
else
{
cout << "Your monthly bill is: $14.95";
}
break;
case 'C':
cout << "Your monthly bill is: $19.95";
break;
default:
break;
}
cin.get();
return 0;
}

Your test for A, B, or C is wrong
while (package != 'A' || package != 'B' || package != 'C')
should be
while (package != 'A' && package != 'B' && package != 'C')

Consider your expression:
while (package != 'A' || package != 'B' || package != 'C') {
Let package have the value 'A'.
This evaluates to
false || true || true
which is of course true.

This line always evaluates to true:
while (package != 'A' || package != 'B' || package != 'C')
it should probably be:
while (package != 'A' && package != 'B' && package != 'C')

You should be checking to see if cin has been able to stream a value of the desired type, ala if (cin >> my_int), then using std::cin.clear() after an erroneous input before getting them to reenter the value. Otherwise, garbage values like say some text input that can't be converted to an int leave std::cin in an error state and the next std::cin >> xxx isn't even attempted.

The "while" will only loop when you want it to, but the "if" will always fire; is that what you mean? The "if" concerning A, B, or C always fires because you've used "||" meaning "or" to link conditions. It is always true, for any value of your variable, that it's not A, or not B, or not C!

First of all, this code:
//Validating user input-must enter A, B or C
if (package != 'A' || package != 'B' || package != 'C')
{
cout << "\nPlease enter A, B or C(capitalized).";
cout << "\n\nWhat package did you buy?: ";
cin >> package;
}
won't work, because (1) you're comparing a string (package) to characters, and (2) you're using || (or) instead of && (and). Also (3) you probably want "while" instead of "if".
The while loop worked fine for me.

cin >> package;
//Validating user input-must enter A, B or C
while (package != 'A' || package != 'B' || package != 'C')
{
cout << "\nPlease enter A, B or C(capitalized).";
cout << "\n\nWhat package did you buy?: ";
cin >> package;
}
What if the package value is B entered inside the loop. It satisfies the first condition package != 'A' and since it is an OR operation after it( true || false || true leads to true), loop enters. You should use && instead. So, change
while (package != 'A' && package != 'B' && package != 'C')
{
// .....
}

Related

Variable 'maxHours' being used without being initialized

So I'm developing a program where I need to get information about what month the user has purchased for a subscription package cellphone plan. Based on the hours of the chosen month and the number of hours the user used within that given month I need to calculate their total costs.
My problem arises when I try to use the month that the user had given and assign that month the maxHours in it. For example, January has 31 days therefore it has 744 hours. If they enter a value larger than maxHours, so in this case anything > 744, I want the program to terminate.
When using visual studio i get the error "The variable 'maxHours' is being used without being initialized. Although I initialized it following the conditions of the if statements.
#include <iostream>
using namespace std;
int main()
{
char package;
int month;
float hours;
int maxHours;
float extraHoursA = 2.0, extraHoursB = 1.0;
float costA, costB, costC;
//Supplies the user with the details of each package option
cout << "Which package plan did you purchase? Your options are:" << endl;
cout << "Package A: For $9.95 per month 10 hours of access are provided. Additional hours are $2.00 per hour." << endl;
cout << "Package B: For $14.95 per month 20 hours of access are provided. Additional hours are $1.00 per hour." << endl;
cout << "Package C: For $19.95 per unlimited access is provided." << endl << endl;
//Asks for the chosen package option
cout << "Please enter the letter of your chosen package: ";
cin >> package;
//Validates the chosen package option
if (package != 'a' && package != 'A' && package != 'b' && package != 'B' && package != 'c' && package != 'C')
{
cout << "You have entered an invalid option, please try again.";
return 0;
}
//Confirms with user the chosen package option
else if (package == 'a' || package == 'A');
{
cout << endl << "You chose package A. For $9.95 per month 10 hours of access were provided. Additional hours were $2.00 per hour." << endl << endl;
}
//Asls for the month in which the package was used
cout << "Which month did you utilze your plan for? Please enter the month: ";
cin >> month;
if (month <= 0 || month > 12)
{
cout << endl << "You have entered an invalid month, please try again.";
return 0;
}
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 11)
{
maxHours = 744;
}
else if (month == 4 || month == 6 || month == 9 || month == 11)
{
maxHours = 720;
}
cout << endl << "You utilized the plan in the month of " << month << endl;
cout << "How many hours did you use? Please enter the amount of hours you utilized ";
cin >> hours;
if (hours > maxHours)
{
cout << "Error: Hours used cannot exceed " << maxHours << " in the " << month << "th month!";
return 0;
}
if (hours < 0)
{
cout << "Error: Hours used cannot be less than 0";
return 0;
}
return 0;
}
maxHours is initialized under the if and else if block. If neither of the condition is met, maxHours will stay un-initialized. That is the reason you are getting this error. If you try to print the value of a variable that is not initialized, then you will get a garbage value.
Better initialize it with int number
At the declaration, do the initialization:
int maxHours = 0;

Difficulty with While loop in C++

I have difficulty with my C++ assignment.
The first problem is at the end of the loop with (answer != "yes" && customers <= 5), the output is not working, because it gives both condition. The second problem is that the code is too complex and need to be simplify (any suggestion)?
The code:
#include <iostream> // Access output and input stream
#include <string> // Access string variable
using namespace std;
int main() {
int characters, food, movie, customers=0; //Declare variables
char gender; //Declare variables
string name, answer; //Declare variables
cout <<"Is there a customer? <enter yes if there is and anything else to end program>"<<endl;
cin>>answer;
while (answer == "yes")
{
customers++;
cout <<"\nWhat is your name dear? ";
cin >> name;
cout <<"Well "<<name<<", welcome to my salon!\n";
cout <<"I will ask you a few questions and your answers will determine which haircut I will give you.\nPlease enter your choice by using the character between < > next to your choice.\n\n";
cout <<"Are you <m>ale or <f>emale? ";
cin >>gender;
if (gender == 'm')
{
cout <<"Are you a Super Hero<0> or a Super Villain<1>? ";
cin >>characters;
if (characters == 1)
{cout <<name <<", You should get a mohawk.\n";}
else if (characters == 0)
{
cout <<"OK "<<name<<", do you prefer steak<0> or sushi<1>? ";
cin >>food;
if (food == 0)
cout <<name<<", You should get a flat top.\n";
else if (food == 1)
cout <<name<<", You should get a pompadour.\n";
}
cout <<"Hope you like it!!\n------------\n";
}
else if (gender == 'f')
{
cout <<"Are you a Super Hero<0> or a Super Villain<1>? ";
cin >>characters;
if (characters == 1)
{cout <<name <<", You should get a mohawk.\n";}
else if (characters == 0)
{
cout <<"OK "<<name<<", do you prefer anime<0> or sitcom<1>? ";
cin >>movie;
if (movie == 0)
cout <<name<<", You should go with bangs.\n";
else if (movie == 1)
cout <<name<<", You should go with feathered.\n";
}
cout <<"Hope you like it!!\n------------\n";
}
cout <<"Any other customers? <enter yes if there are and anything else if I am done for the day> "<<endl;
cin >>answer;
if (answer != "yes" && customers >= 5)
cout<<"\nWell that was a good day! I had " <<customers<<" customer<s> today. Tomorrow is another day ..."<< endl;
else if (answer != "yes" && customers < 5)
cout<<"\nWell that was a poor day! I had " <<customers<<" customer<s> today. Tomorrow is another day ..."<< endl;
}
cout<<"\nWell that was a poor day! I had " <<customers<<" customer<s> today. Tomorrow is another day ..."<< endl;
return 0;
}
Put the if else condition outside the while loop and remove cout<<"\nWell that was a poor day! I had " <<customers<<" customer<s> today. Tomorrow is another day ..."<< endl; outside your while loop.
while (answer == "yes")
{
...
}
if (customers >= 5)
cout<<"\nWell that was a good day! I had "
<<customers
<<" customer<s> today. Tomorrow is another day ..."
<< endl;
else
cout<<"\nWell that was a poor day! I had "
<<customers
<<" customer<s> today. Tomorrow is another day ..."
<< endl;

Constructing do while loop to handle account numbers not working C++

I'm trying to use a do while loop to evaluate account numbers. A valid account number has to have 5 digits and start with the letters R or B, not case sensitive.
Valid account number examples:
r90000
B10101
R88888
b77777
invalid account number examples:
y90000
r888822
This is the loop I've made, and I can't figure out what's wrong with my parameters that's causing it to repeat over and over again, never excepting an account number.
char accountType;
int accountNum;
cout << "Please enter your account number." <<endl;
cout << ">> ";
cin >> accountType >> accountNum;
cout <<endl;
do
{
cout << "That is not a valid account number. Please enter your account number." <<endl;
cout << ">> ";
cin >> accountType >> accountNum;
cout <<endl;
}while ( (accountNum <= 9999) || (accountNum >= 100000) && (accountType != 'r') || (accountType != 'R') || (accountType != 'b') || (accountType != 'B') );
Any ideas?
Your conditions for repeating the loop are any of:
accountNum <= 9999
accountNum >= 100000 && accountType != 'r'
accountType != 'R'
accountType != 'b'
accountType != 'B'
But for every character, at least two of (3), (4), and (5) are true, so you'll always repeat.
You need to loop while all of the accountType checks fail OR any of the accountNum checks fail. That is, any of:
accountNum <= 9999
accountNum >= 100000
accountType != 'r' && accountType != 'R' && accountType != 'b' && accountType != 'B'

How can I set a default value when incorrect/invalid input is entered?

The direction in the project states the following:
“For the activity level, if the input is not valid, print a message and tell the user you are assuming that they are sedentary.”
The following is my current code, I am trying to get it to default to "Sedentary" which the user can input as SA or sa. The default for an invalid input is supposed to make the program default to sedentary, and I am a little confused whether I am on the right track or not.
else if (gender == 'F' || gender == 'f') {
cout << "Please enter your Height in inches. (You may include a decimal) ";
cin >> height;
cout << "Please enter your Weight in pounds as a whole number. ";
cin >> weight;
cout << "Please enter your Age in years. ";
cin >> age;
cout << endl;
if (activity_level = 'SA' || activity_level = 'sa' || activity_level = 'LA' || activity_level = 'la' ||
activity_level = 'MA' || activity_level = 'ma' || activity_level = 'VA' || activity_level = 'va') {
cout << "Please enter your activity level." << endl << endl;
cout << "You may enter one of the following choices." << endl << endl;
cout << "Sedentary (Little or no exercise) \"SA\" or \"sa\" " << endl;
cout << "Lightly Active (Light exercise/sports 1-3 days a week) \"LA\" or \"la\" " << endl;
cout << "Moderately Active (Moderate exercise/sports 3-5 days a week) \"MA\" or \"ma\" " << endl;
cout << "Very Active (Hard exercise/sports 6-7 days a week) \"VA\" or \"va\" " << endl << endl;
cout << "Enter your activity level now. ";
cin >> activity_level;
cout << endl;
}
// Output for the message to defualt to Sedentary if you do not select activity level throught he proper input.
else {
activity_level =
cout << "I'm sorry I did not recogonize that activity level. We will assume a sedentary amount of exercise. "
}
}
Basically I am wondering, if what I am doing; the use of another if statement within the else if statement, will work out, and I am wondering if the way I have it set up at the moment will produce the required result.
If you want to default to SA then you could do this:
//Assume activity_level has had something assigned to it, to compare to.
if (activity_level == "SA" || activity_level == "sa" || activity_level == "LA" || activity_level == "la" ||
activity_level == "MA" || activity_level == "ma" || activity_level == "VA" || activity_level == "va")
{
//Do stuff if input is valid
}
// Output for the message to defualt to Sedentary if you do not select activity level throught he proper input.
else
{
activity_level = "SA";
std::cout << "I'm sorry I did not recogonize that activity level. We will assume a sedentary amount of exercise.";
}
Also something with single quotes can only be a single char, anything else needs double quotes around it, because it's a string.
You must check the variable `activity_level' after it has been assigned a value. Also you should use == to make comparisons. And you could use the ! operator to negate a condition.

Multiple conditions in C++ if statement

I am very new to the concept of programming in C++. I am wanting to have a multi condition if statement using the || (or) and the && (and) in one statement. When I ask my college professor about it. She told it was possible and then insulted my limited knowledge on the subject. All examples I have access to show a multi && statement and only one showing the ||. It does not show them being used together. I would like to learn how to get the line working. I will attach the code I have. The problem area is the last bit of coding.
# include <iostream>
# include <cstring>
using namespace std;
main()
{
const int maximumHours = 774;
char customerPackage;
double hoursUsed = 0,
packageA = 9.95,
packageB = 14.95,
packageC = 19.95,
overPackageA = 2.00,
overPackageB = 1.00,
overTime = 0,
amountDue = 0,
excessCharged = 0;
cout << "Please enter the customer's package: ";
cin >> customerPackage;
switch (customerPackage)
{
case 'a' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
case 'A' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
case 'b' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
case 'B' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
case 'c' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
case 'C' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
default: cout << "Error."
<< " Please enter the customer's purchased package: ";
cin >> customerPackage;
}
if ( customerPackage ='a' || customerPackage ='A' && hoursUsed >= 10)
amountDue = packageA;
else
overTime = packageA - hoursUsed;
excessCharged = overTime * overPackageA;
amountDue = packageA + excessCharged;
}
Your problem is that && has higher precedence than || so you need parens. As noted in a comment you also need to use == instead of assignment (=):
if ( (customerPackage =='a' || customerPackage =='A') && hoursUsed >= 10)
Others have already helped you with the problem you've noticed. I'll start with a separate problem you apparently haven't noticed (yet):
else
overTime = packageA - hoursUsed;
excessCharged = overTime * overPackageA;
amountDue = packageA + excessCharged;
If you want all three of those statements controlled by the else, you need to enclose them in braces to create a compound statement:
else {
overTime = packagA - hoursUsed;
excessCharged = overTime * overPackageA;
amountDue = packageA + excessCharged;
}
As it stands right now, your code is really:
else
overTime = packageA - hoursUsed;
excessCharged = overTime * overPackageA;
amountDue = packageA + excessCharged;
I.e., the computations for excessCharged and amountDue are carried out regardless of whether the condition in the if statement was true or false.
I'd also note that your switch statement doesn't really accomplish much:
switch (customerPackage)
{
case 'a' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
case 'A' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
case 'b' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
case 'B' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
case 'c' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
case 'C' :
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
default: cout << "Error."
<< " Please enter the customer's purchased package: ";
In particular, you take exactly the same action for all the cases (except the default). You can simplify this a bit by using fall-through cases:
switch (customerPackage) {
case 'a':
case 'A':
case 'b':
case 'B':
case 'c':
case 'C':
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
break;
default:
cout << "Error " /* ... */;
}
Alternatively, you might consider something like:
static const char valid[] = "aAbBcC";
if (strchr(valid, userPackage)) {
cout << "Please enter the number of hours used: ";
cin >> hoursUsed;
}
else {
std::cout << "Error: Please enter the customer's purchased package";
std::cin >> userPackage;
}
Personally, however, I'd structure things a bit differently: first get one valid input, then get the next:
do {
std::cout << "Please enter the customer's purchased package (a, b, or c): ";
std::cin >> userPackage;
} while (!strchr(valid, userPackage));
std::cout << "Please enter the number of hours used: ";
std::cin >> hoursUsed;
if (tolower(customerPackage == 'a') && hoursUsed >= 10)
// ...
if ( customerPackage ='a' || customerPackage ='A' && hoursUsed >= 10)
You are so close to having the right answer. Let me give you two hints:
The = operator is not the same as the == operator. = is the assignment operator. It evaluates its right-hand-side and stores the result in the variable named on its left-hand-side. You want ==, the equality operator. It tests to see if its right-hand side and its left-hand-side are equal.
Use parenthesis ( ... ) to enforce your order-of-evaluation intention. You clearly mean to say "If either customerPackage is 'a' or it is 'A', and also hoursUsed is sufficiently large, then ...".
Try this line:
if ( (customerPackage == 'a' || customerPackage == 'A') && hoursUsed >= 10)
You can use parentheses to specify the order in which the boolean operators are executed. You probably want to evaluate the || first, so you'd use:
if ((customerPackage == 'a' || customerPackage == 'A') && hoursUsed >= 10)
The && is normally evaluated first by default, because it has higher precedence, so your code is equivalent to this:
if (customerPackage == 'a' || (customerPackage == 'A' && hoursUsed >= 10))
Also, as noted in the comments, use == for comparison and = for assignment.
With the new problem you're having (in the other question you asked), you'll need some restructuring.
if ( (customerPackage == 'b' || customerPackage == 'B') && hoursUsed <= 20)
amountDue = packageB;
else
{
/* calculations */
}
is not correct, that should be
if ( customerPackage == 'b' || customerPackage == 'B')
{
if (hoursUsed <= 20)
{
amountDue = packageB;
}
else
{
/* calculations */
}
}
Otherwise the first statement will only be executed when package=B AND hour=20, otherwise the calculations will be done in all other cases, like when package is A, or C.
Hope this helps!