if statement fall through output issues - c++

whenever I enter a different case and enter an hour that meets the if statements requirements the else also gets printed, help I just need one output from each different situation.
the example below is the error I get.
ex: enter 'a' enter '11' output 'the amount due is 11.95' 'the amount due is 9.95'
//Libraries
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
//Global Constants
//Functioning Prototypes
//Execution Begins here
int main(int argc, char *argv[]){
//Declare Variables
char pack;
int hours;
float due;
//prompt user
cout<<"Please choose one monthly internet subscription package: a, b, or c\n";
cin>>pack;
cout<<"Enter how many hours were that month used\n";
cin>>hours;
//process
cout<<setprecision(2)<<fixed<<showpoint;
switch (pack){
case 'a':
if (hours>=10 && hours<=744){
hours=(hours-10)*2;
due=hours;
due+=9.95;
cout<<"The amount due is $"<<due<<endl;
}
else if (hours>=744){
cout<<"ERROR: a month cannot exceed 744 hours\n";
}
else ( hours<=10);{
due=9.95;
cout<<"The amount due is $"<<due<<endl;
}
break;
case 'b':
if (hours>20 && hours<744){
hours=(hours-20);
due=hours;
due+=14.95;
cout<<"The amount due is $"<<due<<endl;
}
else if (hours>=744){
cout<<"ERROR: a month cannot exceed 744 hours\n";
}
else (hours<=20);{
due=14.95;
cout<<"The amount due is $"<<due<<endl;
}
break;
case 'c':
if (hours>=744){
cout<<"ERROR: a month cannot exceed 744 hours\n";
}
else if (hours<744);{
due=19.95;
cout<<"The amount due is $"<<due<<endl;
}
break;
}
system("PAUSE");
return 0;
}

else (hours<=20);{
due=14.95;
cout<<"The amount due is $"<<due<<endl;
}
is equivalent to:
else (hours<=20) {
//Do nothing
}
{
due=14.95;
cout<<"The amount due is $"<<due<<endl;
}
You need to remove the ";". Otherwise, the last code block will always be executed because it isn't part of the else block.

Related

How to scan for a letter in c++ instead of a number?

My code prompts the user to input 0 or 1 as an integer in answer to one of the questions. I want the user to type Y or N. I tried to create a char variable, but I am not getting it right. It says y and n is not declared. I know it's a basic question, but I have just started learning c++.
Here is my code and below that the prompts, inputs, and output as well as a screenshot.
#include <iostream>
using namespace std;
int main() {
int a; // number of classes held
int b; // number of classed attended
int percent;
cout<<"Number of classes held "<<endl;
cin>>a;
cout<<"Number of classes attended "<<endl;
cin>>b;
percent = (b*100)/a;
if (percent>75 && percent<=100) {
cout<<"Congratulation you are allowed to sit in the examination your attendence is "<<percent<<"%";
} else if (percent<75) {
int m;
cout<<"Do you have any medical cause? (Respond in '1' for yes or '0' for no) "<<endl;
cin>>m;
if (m==1) {
cout<<"You are allwed due to a medical cause your percentage is "<<percent<<"%";
} else if (m==0) {
cout<<"You are not allowed to sit in the examination your percentage is "<<percent<<"%";
} else if (m!=1 && m!=0) {
cout<<"Invalid Responce";
}
} else {
cout<<"invalid attendence";
}
return 0;
}
cout<<"Number of classes held "<<endl;
cin>>a;
cout<<"Number of classes attended "<<endl;
cin>>b;
percent = (b*100)/a;
if (percent>75 && percent<=100) {
cout<<"Congratulation you are allowed to sit in the examination your attendence is "<<percent<<"%";
} else if (percent<75) {
int m;
cout<<"Do you have any medical cause? (Respond in '1' for yes or '0' for no) "<<endl;
cin>>m;
if (m==1) {
cout<<"You are allwed due to a medical cause your percentage is "<<percent<<"%";
} else if (m==0) {
cout<<"You are not allowed to sit in the examination your percentage is "<<percent<<"%";
} else if (m!=1 && m!=0) {
cout<<"Invalid Responce";
}
} else {
cout<<"invalid attendence";
}
return 0;
}
Here is the output of my code:
Number of classes held
100
Number of classes attended
53
Do you have any medical cause? (Respond in '1' for yes or '0' for no)
1
You are allwed due to medical cause your percentage is 53%
screenshot of code and output
Try using char:
char m;
std::cin >> m;
if (m == 'y')
// do something
else if (m == 'n')
// do something else
I think I understood the problem. To do this, you can also include the string library with #include <string>. So you can enter the "y" and "n" values you want as strings.
I leave a sample code for you.
#include <iostream>
#include <string>
using namespace std;
int main() {
string answer;
cout << "yes or no=? ";
cin >> answer;
if(answer == "y")
{
cout << "YES!";
}
else if(answer == "n")
{
cout << "NO!";
}
else {
cout << "TRY AGAIN!";
}
return 0;
}

Encountering Infinite loop in case of string handling

#include<iostream>
#include<cstdio>
using namespace std;
class Time
{
int hours=0,scan_hours=0;
int minutes=0,scan_minutes=0;
public:
void input_time_in_format_1(void)
{
cout<<"\n\t Enter the time in the format hh:mm A.M./P.M.: ";
if(scanf("%d",&hours)==1)
{
if(scanf(":%d A.M.",&minutes)==1)
{
hours=(hours+12)%24;
if(hours>13||minutes>60||hours<0||minutes<0)
{
cout<<"\n\t Wrong entry";
hours=minutes=0;
}
else
cout<<"\n\t Your time has been accepted";
}
else if(scanf(":%d P.M.",&minutes)==1)
{
if(hours>13||minutes>60||hours<0||minutes<0)
{
cout<<"\n\t Wrong entry";
hours=minutes=0;
}
else
cout<<"\n\t Your time has been accepted";
}
else
{
cout<<"\n\t Wrong entry";
hours=0;
minutes=0;
}
}
else
{
cout<<"\n\t Wrong entry";
hours=0;
}
}
void input_time_in_format_2(void)
{
cout<<"\n\t Enter the time in the format hh:mm hours: ";
if(scanf("%d",&hours)==1 && hours<24)
{
if(scanf(":%d hours",&minutes)==1 && minutes<60)
cout<<"\n\t Your time has been accepted";
else
{
cout<<"\n\t Wrong entry";
hours=minutes=0;
}
}
else
{
cout<<"\n\t Wrong entry";
hours=0;
}
}
void show_time_in_format_1(void)
{
cout<<"\n\t Showing time in 24 hours format: "<<hours<<":"<<minutes<<" hours";
}
void show_time_in_format_2(void)
{
if(hours>12)
cout<<"\n\t Showing time in 12 hours format: "<<(hours%12)<<":"<<minutes<<" P.M.\n\n";
else
cout<<"\n\t Showing time in 12 hours format: "<<hours<<":"<<minutes<<" A.M.\n\n";
}
void add_time(void)
{
cout<<"\n\t Please enter the hours and minutes respectively";
cin>>scan_hours;
cin>>scan_minutes;
if(minutes+=scan_minutes>=60)
{
hours+=(scan_hours+1);
hours%=24;
}
else
{
hours+=(scan_hours);
hours%=24;
}
}
};
int main()
{
Time t1;
int choice;
do
{
cout<<"\n\t\t\t --Welcome--"<<"\n\n\t Please enter your choice \n\t1.Input time in 12 hours format\n\t2.Input time in 24 hours format\n\t3.Show time in 12 hours format\n\t4.Show time in 24 hours format\n\t5.Add user input time\n\t6.Exit....-->";
cin>>choice;
switch(choice)
{
case 1:cin.ignore();
t1.input_time_in_format_1();
break;
case 2:
t1.input_time_in_format_2();
break;
case 3:
t1.show_time_in_format_2();
break;
case 4:
t1.show_time_in_format_1();
break;
case 5:
t1.add_time();
break;
case 6:
cout<<"\n\t Thank You";
exit(0);
default:
cout<<"\n\n\t Wrong entry";
break;
}
}while(1);
return 0;
}
This is my program to accept a date from the user and to print it in different format. If I choose the case 1 whenever I want to give any input,weather it be correct or wrong, it leads me to an infinite loop. I couldn't find out what's going on. i think I have handled all the exceptions.Feel free to dump it, if you wish.
the most likely cause of the problem is the line:
cin >> choice;
This is failing because the istream contains a newline and this will cause the cin to fail.
Suggest calling:
cin.ignore();
before outputting the prompt/menu then the istream will be empty and the response to the menu, as input by the user, will be placed into the variable `choice;

Simple program - menu is being displayed only once

I am trying to keep a track of total amount of bought groceries.
In my program, every time I buy apples, cheese, or bread, the program should continue with displaying the menu again.
But it keeps asking "How many apples?" after the program has already calculated the total for the apples instead of going back to the menu to choose another item.
Perhaps it has something to do with the type of loop I have used.
I am stuck on trying to figure this out. Any help would be appreciated.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
double BUDGET;
const double apple= .60;
const double lb_cheese= 1.60;
const double loaf_bread = 2.50;
double total;
int count;
char choice;
double amount_left;
cout <<"Welcome! What is the budget for your picnic lunch?"<< endl;
cin>> BUDGET;
cout<<"Choose one of the following"<<endl;
cout<<"-------------------------------------"<<endl;
cout<<" MENU \n "<<endl;
cout<<"A-Apple B-Cheese C-Bread"<<endl;
cout<<" $0.60 $1.50 $2.50 "<<endl;
cout<<"-------------------------------------"<<endl;
cin>> choice;
while ((choice != 'Q') && (total <BUDGET)) //Q is the sentinel value to "quit" the program
{
switch(choice)
{
case 'A':
case 'a':
cout<<"How many apples?";
cin>> count;
total+= (count *apple);
break;
case 'B':
case 'b':
cout<<"How many pounds of cheese ?";
cin>> count;
total+= (count* lb_cheese);
break;
case 'C':
case 'c':
cout<<"How many loafs of bread?";
cin>> count;
total+= (count * loaf_bread);
break;
default:
cout<<"The entry you have entered is not valid, please try again."<<endl;
}
if( total > BUDGET)
{ cout<<"You have exceeded your budget please check your cart.\n\n";
break;
}
cout<<"Your total is: $"<<setprecision((2))<<fixed<<total<<endl;
amount_left= BUDGET-total;
cout<<"You have $"<<setprecision(2)<<fixed<<amount_left<<" left to spend."<<endl;
}
return 0;
}
Displaying menu is out of the loop:
display menu
read option
while (option != quit) {
do some calculations
}
and the menu is therefore displayed only once. You could change it to infinite loop:
while (true) {
display menu
read option
if (choice == 'Q' || total >= BUDGET)
break;
do some calculations
}
Also try to avoid writing functions that are longer than 50 lines, place some logic into some different function and just call this function, decompose it to smaller parts, it will be much easier to read and also much easier to understand.
Yes, get the menu in a loop to display it the number of times you desire and also please remember to initialize your variables as good practice.
Double total=0.00 // initialize.

While Loop Won't loop C++

I can't seem to figure out why this while loop stopped looping. It was doing fine before I moved some code around. Now I got something else working and it just doesn't loop. I've also tried making quit a bool set to true and tried to have it loop while it was true until the user hit 4 to exit in which case it would turn it to false but that didn't work. I also tried adding a while loop to the function of showMenu but that also didn't work. I know it must be something simple I just can't catch it. gggrrrr.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
enum transType { SETUP=1, DEPOSITE, WITHDRAW, EXIT};
int showMenu(double balance);
double transaction(double amount, double balance, transType trans);
int menuSwitch;
int quit=0;
int _tmain(int argc, _TCHAR* argv[]){
int amount=0,balance=0;
while(quit!=4){
showMenu(balance);
switch (menuSwitch){
case DEPOSITE:
cout<<"Enter the amount of deposit: ";
cin>>amount;
cout<<"Your current balance is: "<<transaction(amount,balance,DEPOSITE)<<endl<<endl;
break;
case WITHDRAW:
cout<<"Enter the amount of withdraw: ";
cin>>amount;
if(amount>balance){
cout<<"*** Insufficient funds."<<"Your current balance is: "<<transaction(amount,balance,WITHDRAW)<<endl<<endl;
}
else cout<<"Your current balance is: "<<transaction(amount,balance,WITHDRAW)<<endl<<endl;
break;
case EXIT:
cout<<"Have a Nice Day."<<endl;
quit=4;
break;
}
return 0;
}
}
int showMenu(double balance){
// while(quit==true){
cout<<"Your Online Checking Account System"<<endl;
cout<<"-------------------------------------------"<<endl;
cout<<"Select an option:"<<endl<<endl;
cout<<" 1. Set up the account."<<endl;
cout<<" 2. Deposit Funds into your Account."<<endl;
cout<<" 3. Withdraw Funds out of your Account."<<endl;
cout<<" 4. Exit"<<endl;
cout<<endl<<">>";
cin>>menuSwitch;
switch (menuSwitch){
case SETUP:
cout<<"Enter the balance: ";
cin>>balance;
cout<<endl<<"Your current balance is: "<<balance<<endl<<endl;
break;
}
return balance;
// }
}
double transaction(double amount, double balance, transType trans){
double withdraw = balance-amount;
double deposite = balance+amount;
if(trans=DEPOSITE){
return deposite;
}
else
return withdraw;
}
//return balance;
You return 0 within the switch brackets, ie inside the while loop. Change it so that you return 0 outside of the while loop.

How do we break the loop without adding the sentinel to the average?

As the code stands now, the sentinel is being included in the calculation for the average. Any pointers on how to break the loop without including the sentinel?
#include <iostream>
using namespace std;
int main ()
{
int fahr=0,cent=0,count=0,fav=0;
while (fahr!=-9999)
{
count ++;
cout<<"Input the fahrenheit temp to be converted to centigrade or enter -9999 "<<endl;
cin>>fahr;
cent=(float)(5./9.)*(fahr-32);
cout<<"The inputed fahr "<<fahr<<endl;
cout<<"The cent equivalent "<<cent<<endl;
}
fav=(float)(fav+fahr)/count;
cout<<"Average"<<fav<<endl;
return 0;
}
Make the code run in an infinite loop, and use break to terminate the loop if you see -9999.
#include <iostream>
using namespace std;
int main ()
{
int fahr=0,cent=0,count=0,fav=0;
while (true)
{
count ++;
cout<<"Input the fahrenheit temp to be converted to centigrade or enter -9999 "<<endl;
cin>>fahr;
if (fahr == -9999)
break;
cent=(float)(5./9.)*(fahr-32);
cout<<"The inputed fahr "<<fahr<<endl;
cout<<"The cent equivalent "<<cent<<endl;
}
fav=(float)(fav+fahr)/count;
cout<<"Average"<<fav<<endl;
return 0;
}
Probably you need to add one more line after
cout<<"The cent equivalent "<<cent<<endl;
add:
fav += cent;
and change
fav=(float)(fav+fahr)/count;
to:
fav=(float)fav/count;