Variable 'maxHours' being used without being initialized - c++

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;

Related

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

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.

24 hour clock to standard

I am writing a program for class where it converts from military time to standard. Everything else seems to be working fine until I type in 60 for the minutes. For example if I type 23:60 it gives me 11:60 PM which is incorrect. How do I fix this? I tried checking if minutes == 60 to reset minutes to 0 but I cant figure it out.
#include <iostream>
using namespace std;
void inputData(int&, int&, char&); // this function asks users to input
information
void convertData(int&, int&, char&); // this converts the military time to
standard time
int outputData(int&, int&, char&); // this function puts all the other
information together to output certain data
int main ()
{
int hours, minutes;
char am_pm;
char trueValue;
do
{
inputData(hours, minutes, am_pm); // calls to input function
convertData(hours, minutes, am_pm); // calls to the conversion function
outputData(hours, minutes, am_pm); // calls to function that outputs all
the data
cout << "Would you like another conversion? Type Y or y to repeat." <<
endl;
cin >> trueValue;
}
while (trueValue == 'y'|| trueValue == 'Y');
if (trueValue != 'y' || trueValue != 'Y')
cout << "Thanks for using this converter. Have a nice day." << endl;
return 0;
}
void inputData (int &hours, int &minutes, char &am_pm)
{
cout << "Please enter hours (less than or equal to 24): "; // ask user to
input hours.
do
{
cin >> hours;
if (hours > 24)
cout << "ERROR! Must be less than 24" << endl;
}
while (hours > 24); // end of hours loop
cout << "Please enter minutes (less than or equal to 60): "; // ask user to
input minutes.
do
{
cin >> minutes;
if (minutes > 60)
{
cout << "Must be less than 60. Try again!" << endl;
}
}
while (minutes > 60); //end of minutes loop
cout << endl;
cout << "You have entered: " << hours << ":" << minutes; // display what
user inputs together.
cout << endl;
}
void convertData(int &hours, int &minutes, char &am_pm)
{
if (minutes == 60)
{
hours++; // add an hour to 'hours'
minutes = minutes/60;
}
if (hours < 12)
{
hours = 12-12+1;
}
if (hours > 12)
{
hours = hours - 12; // subtracts anything bigger than 12 to get standard
time. Anything over 12 is PM according to project instruction
am_pm = 'P';
}
else
if (hours == 12)
{
am_pm = 'P';
}
else
am_pm = 'A';
}
int outputData(int &hours, int &minutes, char &am_pm)
{
if (am_pm == 'P')
cout <<"Your standard time is: " << hours << ":" << minutes << " P.M" <<
endl;
else
cout <<"Your standard time is: " << hours << ":" << minutes << " A.M" <<
endl;
}
There's a couple of places you test for minutes > 60. Try minutes >= 60 instead.
Same with hours > 24.
Your if statement for minutes being > 60. Change it to >= 60. Currently your if statement is accepting 60 as a valid condition for minutes.

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')

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.

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