Multiple conditions in C++ if statement - c++

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!

Related

Non integer input causes infinite loop

i created a code for my final project. where in the start the user is asked what calculator to use its either the average calculator or simple calculator. but if the user accidentally entered a non integer it causes in infinite error loop but if its an integer that is not in the choices it works because i created a while loop. i need help what do i need to do to prevent the infinite loop.
cout << 1. average calculator: << endl;
cout << 2. simple calculator: << endl;
cout << Enter the Number << endl;
cin >> choice;
while (choice > 2 || choice <= 1)
{
cout << "Error! Please choose a number between 1 and 2 only." << endl;
cout << "Enter the number again:";
cin >> choice;
}
You need to clear the input buffer. Also the condition in this if statement is incorrect
while (choice > 2 || choice <= 1)
It seems you mean
while (choice > 2 || choice < 1)
The while loop can be rewritten as do-while loop the following way
#include <limits>
//...
bool input_error = false;
do
{
input_error = false;
if ( not ( std::cin >> choice ) )
{
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
input_error = true;
}
else if ( choice < 1 || choice > 2 )
{
input_error = true;
}
if ( input_error )
{
std::cout << "Error! Please choose a number between 1 and 2 only.\n";
std::cout << "Enter the number again: ";
}
} while ( input_error );
Instead of using a while loop, you could use a switch like this
switch(choice //this is the input)
{
case 1:
//the stuff you want to do
break; //always a break
case 2:
//more stuff
break;
default:
//throwing a error
std::cout << "Error, please pick a number between 1 and 2\n";
}
and if you want to repeat until you pick the right number, you could put the switch inside a do while loop like this
do
{
switch(choice)
{
//the stuff
}
}while(choice > 2 || choice < 1);
let's hope this will work
have a nice day.
cout << "1. average calculator:" << endl;
cout << "2. simple calculator:" << endl;
cout << "Enter the Number" << endl;
string stringInput;
getline(cin, stringInput);
int choice = atoi(stringInput.c_str());
while(choice < 1 || choice > 2) {
cout << "Error! Please choose a number between 1 and 2 only." << endl;
cout << "Enter the number again:";
getline(cin, stringInput);
choice = atoi(stringInput.c_str());
}
You should read whole line, store it in string, and then convert that string to integer using atoi(). atoi() expects c-string to be passed so std::string should be converted to c-string. It is done by stringInput.c_str().
I changed while condition(choice > 2 || choice <= 1) to (choice < 1 || choice > 2) because it says to enter number between 1 and 2, but with your condition entering number 1 would print "Error! Please choose a number between 1 and 2 only.".

Clearing input buffer

I am writing a program, the program is basically a guessing game. Computer displays a number and the user has to guess whether their number is higher, lower or correct. I have already made the program and its all dandy, but the only not dandy part is that I cannot figure out how to get rid of the input buffer when the user decides to play the game again. Every time the user wants to play the game, the game starts again but with the same input as the last game. I have tried putting cin.clear() in any spot I could think and also cin.clear(). But it just seems to not work. How do I clear the input?
#include <iostream>
using namespace std;
int main ()
{
int num1 = 100;
char choice;
num1 = num1 / 2;
do
{
cout << "My guess is " << num1 << ". " << "Enter 'l' if your number is lower, 'h' if it is higher, 'c' if it is correct: ";
cin >> choice;
cin.clear();
if (choice == 'h')
{
num1 = num1 + 100;
num1 = num1 / 2;
}
if (choice == 'l')
{
num1 = num1 + num1;
num1 = num1 - 11;
num1 = num1 / 2;
}
if (choice == 'c')
{
cout << "Great! Do you want to play again (y/n)?: ";
cin >> choice;
}
} while (choice != 'c' || choice == 'Y' || choice == 'y' || choice == 'n' || choice == 'N');
return 0;
}
In order to restart the game, you need to reset num1. Put the inital value in a variable that you don't change.
const int init = 100;
char choice;
int num1 = init / 2;
When the computer has guessed correctly:
if (choice == 'c')
{
num1 = init / 2; // reset
cout << "Great! Do you want to play again (y/n)?: ";
cin >> choice;
}
You could also leave the loop condition at:
} while(choice != 'N' && choice != 'n');
You should also work on the divide and conquer algorithm. For the computer to be effective, it should always make a guess in the middle of the range that is still possible, and that's not what it's doing right now. It jumps up and down, even outside the established range. An alternative could be to keep two variables to be able to shrink the possible range effectively. You could also do two separate loops, one inner loop for guessing the number and one outer that only asks the user if he/she wants to play again.
Example:
#include <iostream>
int main() {
const int initlo = 1;
const int inithi = 100;
char choice;
do {
std::cout << "Think of a number [" << initlo << "," << inithi << "]\n";
int numlo = initlo; // initialize the range
int numhi = inithi;
int guess;
do {
guess = (numlo + numhi) / 2; // guess in the middle of the range
std::cout
<< "My guess is " << guess << ". "
<< "Enter 'l' if your number is lower, 'h' if it is higher, 'c' "
"if it is correct: ";
std::cin >> choice;
if(choice == 'h') // must be in the range (guess,numhi]
numlo = guess + 1;
else if(choice == 'l') // must be in the range [numlo,guess)
numhi = guess - 1;
// exit the loop if the user cheats or the answer is correct
} while(numlo <= numhi && choice != 'c');
if(choice == 'c') std::cout << "Great! ";
else std::cout << "Cheater! ";
std::cout << "Do you want to play again (y/n)?: ";
std::cin >> choice;
} while(choice == 'Y' || choice == 'y');
std::cout << "Bye\n";
}

Looping assignment in C++

My assignment is utilizing loops. The program should accept input for the sales of 3 employees (Mary, Tom, and Chris). The flow should be as follows:
Initial? > number of sales to enter > enter sale amounts > display commission for sale at 17% > adds commission and sales to the respective variables >> continue until 'z' is input for inputSalesPerson >> display information
So I am trying to figure out why my return value for the tempComm variable isn't returning the correct value. If i was to enter 't' for variable inputSalesPerson it puts me into the switch case 't' no problem. Input number of sales and that works. But when I get to entering the salesAmount and then displaying commission it will not calculate correctly.
Also if I enter 'z' or 'Z' as the inputSalesPerson it will not end the program. I have a lot to go on this.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int salesT = 0, salesC = 0, salesM = 0;
double amountT = 0, amountC = 0, amountM = 0;
double commT = 0, commC = 0, commM = 0;
double commRate = (17/100);
int num_sales;
double salesAmount, totalSales, tempComm;
char inputSalesPerson;
do
{
cout << "Enter the sales person's initial (\"Z\" to quit): ";
cin >> inputSalesPerson;
while(inputSalesPerson != 't' && inputSalesPerson != 'T' && inputSalesPerson != 'm' && inputSalesPerson != 'M' && inputSalesPerson != 'c' && inputSalesPerson != 'C' && inputSalesPerson != 'z' && inputSalesPerson != 'Z')
{
cin.get();
system("cls");
cout << "Invalid input for employee. Please Input (T)om, (C)hris, (M)ary, or (Z) to End : ";
cin >> inputSalesPerson;
}
switch(inputSalesPerson)
{
case 't' :
case 'T' :
system("cls");
cout << "Enter the number of sales : ";
cin >> num_sales;
while(num_sales < 1 || num_sales > 5)
{
system("cls");
cout << "Invalid number of sales. Please enter a value between 1 and 5 : ";
cin >> num_sales;
}
salesT += num_sales;
for(int i = 0; i<num_sales; i++)
{
cin.get();
system("cls");
cout << "Enter the sale amount : ";
cin >> salesAmount;
while(salesAmount < 0)
{
cin.get();
system("cls");
cout << "Invalid sale amount. Please enter a positive amount : ";
cin >> salesAmount;
}
tempComm = salesAmount + (salesAmount * commRate);
cout << fixed << setprecision(2) << "Commission earned by tom on this sale is : " << tempComm << endl;
cin.get();
amountT += salesAmount + tempComm;
commT += tempComm;
totalSales += amountT;
}
break;
}
}while(inputSalesPerson != 'z' || 'Z');
return 0;
}
****EDIT****
Thank you for the information on single-step debugging. Thanks to that comment I was able to learn about using the debugging tool more in depth and that helped me get everything working a bit better.
I've commented your code at the areas that need fixing. Also, there's a problem with using cin.get() all over the place. I assume that you do this to discard the return character after each input. But if the standard input (cin) is empty when you call cin.get() it will block the program until something is input. This is what happens when you enter more than one num_sales:
for (int i = 0; i<num_sales; i++)
{
cin.get();
It handles the first fine, but on the second loop you get:
Enter the sale amount : 20
Commission earned by tom on this sale is : 23.40
// cin.get() blocks here, with no user instructions to enter the next sale amount
I've commented out all the cin.get(). It will still work the same because the cin operator >> discards whitespaces and newlines, so even if there is a \n newline character still in the buffer, the next time you do something like cin >> num_sales it will discard the newline anyway.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int salesT = 0, salesC = 0, salesM = 0;
double amountT = 0, amountC = 0, amountM = 0;
double commT = 0, commC = 0, commM = 0;
double commRate = (17 / 100.0); // Int divided by int will round to an int.
// commRate is 0.0. Divide by double instead (17 / 100.0)
int num_sales;
double salesAmount, totalSales = 0, tempComm; // totalSales needs to be initialised to
// zero, otherwise it holds a garbage value.
char inputSalesPerson;
do
{
cout << "Enter the sales person's initial (\"Z\" to quit): ";
cin >> inputSalesPerson;
while (inputSalesPerson != 't' && inputSalesPerson != 'T' && inputSalesPerson != 'm' && inputSalesPerson != 'M' && inputSalesPerson != 'c' && inputSalesPerson != 'C' && inputSalesPerson != 'z' && inputSalesPerson != 'Z')
{
//cin.get();
system("cls");
cout << "Invalid input for employee. Please Input (T)om, (C)hris, (M)ary, or (Z) to End : ";
cin >> inputSalesPerson;
}
switch (inputSalesPerson)
{
case 't':
case 'T':
system("cls");
cout << "Enter the number of sales : ";
cin >> num_sales;
while (num_sales < 1 || num_sales > 5)
{
system("cls");
cout << "Invalid number of sales. Please enter a value between 1 and 5 : ";
cin >> num_sales;
}
salesT += num_sales;
for (int i = 0; i<num_sales; i++)
{
//cin.get();
//system("cls");
cout << "Enter the amount for sale number " << i+1 << ": ";
cin >> salesAmount;
system("cls"); // I would put the clear here,
// Otherwise the user can't see the commission made by Tom
while (salesAmount < 0)
{
//cin.get();
system("cls");
cout << "Invalid sale amount. Please enter a positive amount : ";
cin >> salesAmount;
}
tempComm = salesAmount + (salesAmount * commRate);
cout << fixed << setprecision(2) << "Commission earned by tom on this sale is : " << tempComm << endl;
//cin.get();
amountT += salesAmount + tempComm;
commT += tempComm;
totalSales += amountT; // I think you mean to add salesAmount maybe?
}
break;
}
} //while (inputSalesPerson != 'z' || 'Z');
// Even if { this ^^^^} is false, ^^^ this is always
// 'Z' char will convert to bool, any non-zero value is true.
while (inputSalesPerson != 'z' && inputSalesPerson != 'Z');
return 0;
}

track how many times an if statement was used true

I think the question speaks for itself, I'm writing a program in c++ and there is a part where the console asks the user which type of input they want to use
while (loop == 5) {
cout << "\nWould you like to enter a depoist or a check? "; //asks for a choice
cin >> choice;
//determines whether or not to close the program
if(choice == 0 || depo == 0 || check == 0) {
return 0;
}//end close if
//choses which type of input to make
if( choice == 1) {
cout << "\nPlease enter check amount: ";
cin >> check;
check += check;
} else if(choice == 2) {
cout << "\nPlease enter deposit amount: ";
cin >> depo;
depo += depo;
}//end if
}
but how do i keep track of how many times the if statement was true?
You can add a counter and increment it every time you enter the if-statement's true block.
int true_counts = 0;
while (loop == 5){
...
if( choice == 1){
true_counts++;
...

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

/*********************************************************
** 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')
{
// .....
}