C++ While statement not working with string and "or" - c++

I'm new to C++, teaching myself via youtube and some books I bought. I can not for the life of me figure out why the 2nd while statement will not work. from a mathematical stand point I feel it should work. If month does not = june or july then do the if else statement. But even when I run the right answer it always runs the if not the else. I feel it has something to do with it being a string, so I tested it without the or "||" and it worked. So maybe it has to do with combining strings and or statements. So did research on using these together and could not find much. Thanks for the help.
int main()
{
int year;
int day = 0;
string month = "x";
do
{
if (day == 0)
{
cout << "hello" << endl;
cout << "Please Enter your B-Day as Day, Month, Year" << endl;
cout << "day" << endl;
cin >> day;
}
else
{
cout << "Please enter a correct day" << endl;
cin >> day;
}
} while (day > 31 || day < 1);
do
{
if (month == "x")
{
cout << "Please enter the month you were born" << endl;
cin >> month;
}
else
{
cout << "Please Enter a correct Month." << endl;
cin >> month;
}
}
**while (month != "june" || month != "july");**
return 0;
}

If you do:
while (month != "june" && month != "july");
Or alternatively,
while (!(month == "june" || month == "july"));
Rather than:
while (month != "june" || month != "july");
Your program will be working fine even with multiple logical OR.

while (month != "june" || month != "july");
There is something called short-circuit evaluation in C++ which will in this case will not evaluate the right of || if the first operand returns true. Likewise for &&, it will not evaluate right operand if first is false. So be sure how you want the logic to behave and write the code.

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;

Trying to create a calendar using switch and if statement to check user input then outputs the day

So I'm trying to create a calendar that asks for the user's chosen month and date numerically using switch statement and then I tried to use if statement to check the user's date input and if it matches it displays the day.
When i run it it always prints Sunday even though i inputted the date for a Monday. What am I missing?
Here is my code
void UserInput()
{
cout << "\nPlease enter a numerical value of a month e.g. May=5, December=12: \n";
cin >> Month;
cout << "\nPlease enter a Date: \n";
cin >> Date;
}
void MagicCalendar()
{
switch(Month)
{
case 1:
if(Date == 6 || 13 || 20 || 27)
{
cout << " It's Sunday!!!";
break;
}
if(Date == 7 || 14 || 21 || 28 ) <-- the problem is probably here idk if its the operand or the if statement itself
{
cout << " It's a MOFO MONDAY GO KYS NOW!";
break;
}
else if(Date ==)
{
cout << " It's a Tuesday and kinda like a monday but yeah...";
break;
}
else if(Date ==)
{
cout << " It's Wednesday and I know that you can feel it!";
break;
}
else if(Date ==)
{
cout << " It's a THURSDAY!! getting warmer :D";
break;
}
else if(Date ==)
{
cout << " It's FRIDAY!! GO GET SHITFACED YOU DESERVE IT :D";
break;
}
else if(Date ==)
{
cout << " It's SATURDAY BABY! go cry in a corner while suffering from Hungover...";
break;
}
break;
}
}
if(Date == 6 || 13 || 20 || 27)
Wrong syntax
Correct:
if(Date == 6 || Date == 13 || Date == 20 || Date == 27)
Similar to other lines in your code.

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;

forever loop... not clearing user input correctly?

when user inputs 'y' or 'Y' for "Do you wish to enter another year? (Y/N): ", loops "the month has 0 days" forever. Why?
I tried to look at the values and it seems like the values stored are being used again. Maybe I am not using cin.clear() correctly?
//variables
bool ucontinue = true; //answer to continue
int year = 0;
int month = 0;
int days = 0;
char answer = 'a';
//loop
while (ucontinue == true)
{
/*
Enter a year (Must be a positive integer): 2016
Enter a month (Must be a between 1 and 12): 2
The month has 29 days.
Do you wish to enter another year? (Y/N): y
*/
//year input
while (year <= 0)
{
cout << "Enter a year (Must be a positive integer): ";
cin >> year;
}
//month input
while (month <= 0)
{
cout << "Enter a month (Must be a between 1 and 12):";
cin >> month;
}
//# of days in the month
cout << "The month has " << days << " days." << endl << endl;
//continue?
while (answer != toupper('y') && answer != toupper('n'))
{
cout << "Do you wish to enter another year? (Y/N): ";
cin >> answer;
answer = toupper(answer);
if (answer == toupper('n'))
{
ucontinue = false;
}
}
cin.clear();
}
you code loops forever because of you while loops the the first time you run the program it works fine but the second time it goes around all the values are set for example the second time you go through the loop this while statement
while (year <= 0)
{
cout << "Enter a year (Must be a positive integer): ";
cin >> year;
}
won't run because year is already greater than 0 and this happens for all the while statements in your code. what would work is if you have do while statements instead of while statements because do while statements will run through the loop once before testing the condition it. like this:
do
{
cout << "Do you wish to enter another year? (Y/N): ";
cin >> answer;
answer = toupper(answer);
if (answer == toupper('n'))
{
ucontinue = false;
}
}while(answer != 'Y' && answer != 'N');
If I understand correctly you do the following:
Enter a year (Must be a positive integer): 2017
Enter a month (Must be a between 1 and 12):5
The month has 0 days.
Do you wish to enter another year? (Y/N): y <ENTER>
and your program loops. What happens it the following:
cin.clear();
is executed and your loop starts again. At this point year and month are still set. So when in the new loop iteration the line
while (year <= 0)
is encountered the condition is false and the loop continues to
while (month <= 0)
for this line the same is true. After that
cout << "The month has " << days << " days." << endl << endl;
is printed and the condition in
while (answer != toupper('y') && answer != toupper('n'))
is checked. As I have just entered y this condition is not true and
cin.clear();
is executed next, after this the loop restarts ad infinitum.
Your programs have many problems
you never updated or input something on the days variable so it will always be 0 as you set it in the beginning of the program
if (answer == toupper('n')) can be reduced to if (answer=='N')

Leap year program doesn't seem to run

Question - A year with 366 days is called a leap year. A year is a leap year if it is divisible by four (for example, 1980), except that it is not a leap year if it is divisible by 100 (for example, 1900); however, it is a leap year if it is divisible by 400 (for example, 2000). There were no exceptions before the introduction of the Gregorian calendar on October 15, 1582. Write a program that asks the user for a year and computes whether that year is a leap year.
This is what I have so far, and the program doesn't seem to run for years greater than 1582. Could someone help me out why? Thanks a bunch
using namespace std;
int main()
{
cout<< "Pleas enter a year: " <<endl;
int year = 0;
cin >> year;
if (year <= 1581)
{
if (year % 4 == 0)
{
cout << "It's a leap year, wow! " << endl;
}
else
{
cout << "It's not a leap year " << endl;
}
}
else if (year > 1581)
{
if (year % 4 == 0)
{
if (year % 100 == 0)
{
cout<< "It is not a leap year " << endl;
}
else if (year % 400 == 0)
{
cout<< "It is a leap year, Wow!" << endl;
}
}
}
else
{
cout<< "You entered a wrong year number "<< year<< endl;
}
return 0;
}
You are making it very complex. I don't think you need to care about whether the year is greater than 1582 or not (for a 4 digit number) provided that a leap year is one which is:
• Divisible by 400
OR
• NOT divisible by 100 AND divisible by 4.
Using unnecessary nested ifs can make your code long and error prone. Try this method:
#include<iostream.h>
int main(){
int y=0;
cout << "Enter a year\n";
cin >> y;
cout <<"\n"<<y;
if(y%400==0 || (y%100!=0 && y%4==0))
cout <<" is a leap year";
else
cout <<" is not a leap year";
return 0;
}
Without check if year > 1582
#include<iostream>
using namespace std;
int main()
{
int year;
cout<< "Please enter a year: " <<endl;
cin >> year;
if( year%25 && !(year&3) || !(year&15) )
cout << "It's a leap year!" << endl;
else
cout << "It's not a leap year!" << endl;
return 0;
}
You are missing a number of cases in the handling of years after 1581.
printing "Not leap year" unless (year % 4 == 0)
The third case where a year divisible by 4 is neither divisible by 100 nor 400
It as simple as you have just not written any code that is run when year is 2004, for example.
You are missing 2 else statement
using namespace std;
int main()
{
cout<< "Pleas enter a year: " <<endl;
int year = 0;
cin >> year;
if (year <= 1581)
{
if (year % 4 == 0)
{
cout << "It's a leap year, wow! " << endl;
}
else
{
cout << "It's not a leap year " << endl;
}
}
else if (year > 1581)
{
if (year % 4 == 0)
{
if (year % 100 == 0)
{
cout<< "It is not a leap year " << endl;
}
else if (year % 400 == 0)
{
cout<< "It is a leap year, Wow!" << endl;
}
// <----------- Here you are missing an else
}
// <----------- Here you are missing an else
}
else
{
cout<< "You entered a wrong year number "<< year<< endl;
}
return 0;
}
I suggest
if ( ((year % 400) == 0)
|| ( ((year % 4) == 0) // or (year & 0x3) == 0
&& ( (year <= 1581)
|| ((year % 100) != 0) )))
cout << "It's a leap year, wow! " << endl;
else
cout << "It's not a leap year " << endl;
or
if ( ((year % 4) == 0) // or year & 0x3 == 0
&& ( (year <= 1581)
|| ((year % 100) != 0)
|| ((year % 400) == 0) ) )
cout << "It's a leap year, wow! " << endl;
else
cout << "It's not a leap year " << endl;
It’s a good idea to simplify your conditionals. A general method for this is to convert to a normal form—either conjunctive or disjunctive—and put the tests that are most likely to short-circuit, first. For simple cases such as this, you can just eyeball it.
In this case, conjuctive normal form is extremely simple:
year%4 == 0 &&
( year < 1582 || year%100 != 0 || year%400 == 0 )
That is, the year is divisible by four and any of the three conditions of the Gregorian calendar reform do not hold. Since the first && term that is false, and the first || term that is true, short-circuit the expression, we want to put the clauses that are most likely to short-circuit, first.
Note that you can code-golf year%100 != 0 to year%100 inside a conditional expression, and year%2000 == 0 to !(year%2000), if you find that easier to read.
It makes sense to move this to a helper function. We can mark it constexpr to give the compiler a hint that it can calculate whether constants are leap years or not at compile-time.
I don't like to post complete answers to what look like homework problems, but that ship has sailed.
#include <cstdlib>
#include <iostream>
using std::cin;
using std::cout;
constexpr bool is_leap(const int year)
{
// Conjunctive normal form:
return ( year%4 == 0 &&
( year < 1582 || year%100 != 0 || year%400 == 0 ) );
}
int main()
{
int year = 0; // Used only within the body of the loop that sets it.
while (cin >> year)
cout << year
<< ( is_leap(year) ? " is a leap year.\n"
: " is not a leap year.\n" );
return EXIT_SUCCESS;
}
Even for a trivial program such as this, there’s a design decision worth thinking about: do we declare int year; uninitialized, or initialize it to a bad value such as int year = 0;? In this case, it’s safe either way, because year is only used inside the body of the loop that sets it. If we don’t initialize it, though, we might later refactor the code to use year outside the loop, and then there might be a code path where year is used before it’s initialized (causing undefined behavior!) On the other hand, if we do initialize year, we might prevent the compiler from noticing that there’s a path where it’s used before it was initialized for real. I personally prefer to initialize to an invalid value and assert that it has been updated before use.
Or you can simply write the following program:
#include<iostream>
using namespace std;
int main()
{
int year;
cout << "Enter year: ";
cin >> year;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
cout << "It is a leap year" << endl;
}
else{
cout << "It is not a leap year" << endl;
}
return 0;
}