c++ compiler ignoring first if statement - c++

I am a newby at this and am working on my fist if/else program. I am having trouble getting the first if statement to recognize my input of "r". I tried playing with just one statement at a time I was able to input all the examples of input the teacher gave us with the desired output for residential and business. However when I run the program altogether I have a problem. I select R for residential, 0 for additional connections, 0 for premium channels and instead of output of $18.50 I get the business fee of $75.00. I am sure it is a simple mistake but I can't figure out what I am doing wrong. Can someone who knows how to work an if/else give me some insight on this!
#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const float BASIC_RESIDENTIAL = 18.50;
const float BASIC_BUSINESS = 75.00;
const float CONNECT_RESIDENTIAL = 6.50;
const float CONNECT_BUSINESS = 5.00;
const float PREMIUM_RESIDENTIAL = 7.50;
const float PREMIUM_BUSINESS = 50.00;
char customerType;
int numOfConnections;
int numOfPremiumChannels;
float amountCableBill;
cout << fixed << setprecision(2);
cout << "Residential or Business [R or B]? ";
cin >> customerType;
cout << endl << endl;
cout << "How many Additional Connections? ";
cin >> numOfConnections;
cout << endl << endl;
cout << "Total number of Premium Channels: ";
cin >> numOfPremiumChannels;
cout << endl << endl;
if (customerType == 'R' || customerType == 'r')
{
amountCableBill = BASIC_RESIDENTIAL + CONNECT_RESIDENTIAL * numOfConnections + PREMIUM_RESIDENTIAL * numOfPremiumChannels;
}
//else customerType == 'B' || customerType == 'b'; // unnecessary
{
if (numOfConnections <= 9)
amountCableBill = BASIC_BUSINESS + PREMIUM_BUSINESS * numOfPremiumChannels;
else
amountCableBill = BASIC_BUSINESS + (numOfConnections - 9) * CONNECT_BUSINESS + PREMIUM_BUSINESS *numOfPremiumChannels;
}
cout << "Total amount of Cable Bill: " << amountCableBill << endl << endl;
cout << "Press <ENTER> to end..." << endl;
_getch();
return 0;
}

While the condition else if (customerType == 'B' ...) may be redundant, you still have to put an else before the opening brace of the branch.
It's
if (condition) { code } else { code }

You need else in the condition (unless you want "some other code" to be executed every time)
if (customerType == 'R' || customerType == 'r')
{
//Some Code
}
else //<--Notice else
{
//Some other code.
}

Related

How do I my Program to stop Replicating if wrong input

My program will repeat output: "You are currently on the 2 floor out of 5
The sum of the codes is: 7 and the product of the codes is: 12
Try again before he catches onto you!"
Based on how many wrong characters are added how can I fix this? I have inserted the cin.clear and cin.ignore but it will repeat the part above.
i.e. if I type wasds it will repeat 5x. Any other notes are also appreciated.
#include <iostream>
#include <ctime>
using namespace std;
int PlayerLevel = 0;
int MaxLevel = 5;
bool GamePlay ()
{
srand(time(NULL));
int PlayerGuessA, PlayerGuessB, PlayerGuessC;
int CodeA = rand() % PlayerLevel + PlayerLevel;
int CodeB = rand() % PlayerLevel + PlayerLevel;
int CodeC = rand() % PlayerLevel + PlayerLevel;
int SumofCodes = CodeA + CodeB + CodeC;
int ProductofCodes = CodeA * CodeB * CodeC;
cout << "You are currently on the " << PlayerLevel << " floor out of 5" << endl;
cout << "The sum of the codes is: " << SumofCodes << " and the product of the codes is: " << ProductofCodes << endl;
cin >> PlayerGuessA >> PlayerGuessB >> PlayerGuessC;
int PlayerProduct = PlayerGuessA * PlayerGuessB * PlayerGuessC;
int PlayerSum = PlayerGuessA + PlayerGuessB + PlayerGuessC;
if (PlayerProduct == ProductofCodes && SumofCodes == PlayerSum) {
cout << "Great Job you got this!!!\n" << endl;
++PlayerLevel;
return true;
}
else
{
cout << "Try again before he catches onto you!\n" << endl;
return false;
}
}
int GameStart()
{
string Introduction = "Welcome to your worst nightmare. You are trapped in a murderer's house. You are on the 5th floor and need to get to the first floor to escape.\n";
string Instructions = "He has each door locked behind a security system that requires a 3 number code to disarm it.\nEnter the codes and move foward. Each level will the code will be harder to figure out.\n";
string PlayerStart;
cout << Introduction << endl;
cout << Instructions << endl;
cout << "Would you like to escape? Yes or No" << endl;
cin >> PlayerStart;
if (!(PlayerStart != "Yes" && PlayerStart != "yes")) {
++PlayerLevel;
}
return 0;
}
int main ()
{
if (PlayerLevel == 0) {
GameStart();
}
while (PlayerLevel <= MaxLevel)
{
bool bLevelComplete = GamePlay();
cin.clear ();
cin.ignore();
}
cout << "You Made it out! Now run before he finds out!" << endl;
return 0;
}
When the type of the input doesn't match the type of the variable that it is being extracted to, cin sets the fail bit. Once this happens, all subsequent reads fail until the stream is reset. The offending characters are still left in the buffer, so that needs to be cleared out as well.
Your usage of cin.clear() and cin.ignore() meant that the fail bit was getting reset, but only one offending character was being removed (cin.ignore() ignores one character by default). This is why you saw the output repeating x times for x erroneous characters.
You could do something like this:
while (PlayerLevel <= MaxLevel)
{
bool bLevelComplete = GamePlay();
if (cin.fail())
{
//Input extraction failed, need to reset stream and clear buffer until newline
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
}

How do I make the code not repeat

int main() {
power=1;
while (1 == 1){
tapcost=power*3;
cout << "type upgrade/buy/a" << endl;
cin >> way;
if (way == "upgrade"){
cout << "1. A Power " << "(Costs: " << tapcost << ")" << endl;
cin >> upgr;
if (upgr == 1){
if (0<=money-power*3){
power=power+1;
money=money-power*3;
}
else
cout << "You can't afford that!!!" << endl;
}
}
if (way == "a"){
money=money+power;
}
}
return 0;
}
When I type upgrade and then type anything else other than the variable "1", the code will repeat infinitely.
This is a never-ending problem.
See this question: Infinite loop with cin when typing string while a number is expected
I think your code have some mistakes.
int upgr;
cin >> upgr; // you can type any number you want (-2 147 483 648 / 2 147 483 647)
I suggest you to use getline, cin.getline or fgets instead of cin >> when reading a line.
And just use while(1) or while(true)
You have created an infinite loop by never changing the value of your ‘1’ variable. In some way you need to change that value when iterating through your conditions or else you’ll never get out of your loop.
You could also try out something like that.
char i;
while((std::cin >> i) && i != '1') {
....
}
In your code, while (1 == 1) creates an infinite loop. Since I assume you want this code to keep asking players for their input until they decide to stop, you can add an option exit which breaks out of the loop when the player wants to.
#include <iostream>
int main() {
int power = 1;
int money = 1000;
while (1 == 1) {
int tapcost = power * 3;
std::string way;
std::cout << "type upgrade/buy/a/exit" << std::endl;
std::cin >> way;
if (way == "upgrade") {
std::cout << "1. A Power " << "(Costs: " << tapcost << ")" << std::endl;
int upgr;
std::cin >> upgr;
if (upgr == 1) {
if (0 <= money - power * 3) {
power = power + 1;
money = money - power * 3;
}
else {
std::cout << "You can't afford that!!!" << std::endl;
}
}
}
if (way == "a") {
money = money + power;
}
if (way == "exit") {
break;
}
}
return 0;
}

C++ error: invalid Operands of types 'double' and <unresolved overloaded function type' to binary 'operator'

Im a beginner to programming and I am currently trying to make a conversion program from kg to pounds and vice versa. Im not good at reading the error codes, so can somebody please tell me, what I've done wrong.
#include <iostream>
using namespace std;
int main()
{
char response;
double Kilo_const = 0.45, Pound_const = 2.20, Kilo_output, Pound_output;
double Kilo_input, Pound_input;
cout << "Choose the input unit \nk = kilo and p = pound" << endl;
cin >> response;
if (response == 'k'){
cin >> Kilo_input;
cout << Pound_output = Kilo_input * Pound_const << endl;
}
else (response == 'p'){
cin >> Pound_input;
cout << Kilo_output = Pound_input * Kilo_const << endl;
}
return 0;
}
You problem is Line 21:
cout << Pound_output = Kilo_input * Pound_const << endl;
what you are trying to do here is assign a value to Pound_output and then pass it to cout, which wont work.
You could either do it this way (note the paranthesis! Thx to Alan):
cout << (Pound_output = Kilo_input * Pound_const) << endl;
or
Pound_output = Kilo_input * Pound_const;
cout << Pound_output << endl;
which will first do the conversion and the print it out, or you can do
cout << Kilo_input * Pound_const << endl;
which will not use a variable to store the result, but print it immediately instead.
Same applies to your second conversion.
Also you have a little second mistake with your if clause. The syntax is
if (...) { } else if (...) { }
where you forgot the second if. If that is not present, the else tag has no conditions and will execute whenever the first statement fails. Note the difference:
if (a == 1) { cout << "Execute on a = 1"; } else { cout << "Execute on a != 1"; }
and
if (a == 1) { cout << "Execute on a = 1"; } else if (a == 2) { cout << "Execute on a != 1 and a = 2"; }

Need help creating an equation in C++ to calculate total

My updated code. When I run the code it keeps outputting the prices of all the packages instead of just the one I ask for.
#include <iostream>
using namespace std;
int main() {
// to keep it simple
int choice_a = 995;
int choice_b = 1995;
int choice_c = 3995;
char choice;
int message_units, x=1;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice;
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
do{
cout << "How many message units (enter 1 - 672)" << endl;
// again check this
cin >> message_units;
x++;
}
while(x<2);
if(message_units > 5){
choice_a += 100 * (message_units - 5);
}
cout << "Your total cost is " << choice_a /100 << "." <<choice_a%100 endl
if(message_units > 15){
choice_b += 50 * (message_units - 15);
}
cout <<"Yourtotalcostis"<<choice_b /100 << "." << choice_b%100<<endl;
(You missed an "i" or two, but English is difficult for a non-native speaker.)
Atotalcost = 9.95;
if(messageunits>5)
Atotalcost += 1.0 * (messageunits-5);
EDIT:
There are several ways to deal with amounts of money. One of them is to store an amount as a number of cents, then print it out with care. For example, the amount $2.34 is stored as int price = 234, then to print it out we print price/100 (which is 2), then a decimal point, then price%100 (which is 34, the '%' is the modulo operator, you can look it up). So the code will look like this:
#include <iostream>
using namespace std;
int main()
{
int messageunits;
cout << "how many message units(enter 1 - 672)" << endl;
cin >> messageunits;
int Atotalcost = 995; // cost of package a, in cents
if(messageunits > 5){
Atotalcost += 100 * (messageunits - 5);
}
cout << "Your total cost is " << Atotalcost/100 << "." << Atotalcost%100 << endl;
}
There is still much work to do, but this is a good start.
Along those lines, this example may have a few minor errors and I tried to keep it simple.
#include <iostream>
using namespace std;
int main() {
bool finished = false;
do {
// to keep it simple
double choice_a = 9.95;
double choice_b = 19.95;
double choice_c = 39.95;
char choice;
int message_units;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
// user enters how many units is wanted
cout << "How many message units (enter 1 - 999)" << endl;
// again check this (if homework requires checking input)
cin >> message_units;
// Calculating message units
if (message_units > 5) price += message_units * 1;
else price += message_units * 2; // if $2.00 normal?
// Total Price Output
cout << "Total: " << price << endl;
// Is user done?
char done;
cout << "Do you want to enter another? press enter to continue. If you are done, type something and press enter.";
cin >> done;
// check
if (done != '') {
finished = true;
}
}
while (finished = false);
Alright, that is about it. Two do while loops and the rest. There may be some slight errors while compiling, really, you should try to fix those yourself as this is pretty much the entire assignment...

c++ multiplication game branching statement issue

So I am working on this math console based game. To work on the chapters of this book which I am reading.
I want to be able to make the game quit after using the no option.
The Problem is that when using the no option the program will cycle through once and then quit. I want the program to quit immediately.
I tried adding an else option but it keeps giving me the error code: "(26): error C2181: illegal else without matching if"
Also could anyone tell me how I could add the switch class to add more menus to the game. Would this require more function prototypes?
Thank you for all of your help stack overflow, I'm still learning how to use branching statements!
// multiplicationgame.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void game();
int _tmain(int argc, _TCHAR* argv[])
{
char choice = 0;
game();
while(choice != 'n')
{
cin >> choice;
if (choice == 'y')
cout << "\n\n";
game();
//else
//cout << "later";
//
}
return 0;
}
void game()
{
srand(time(NULL));
int a = rand() % 23;
int b = rand() % 23;
int c = (a * b);
int d = 0;
char choice = 0;
cout <<"What does " << a << " * " << b << " equal?" << endl << endl << endl;
cout << "\n";
while(d != c)
{
if(d != c)
{
cout << "Please enter a number: ";
cin >> d;
}
}
cout << "\n\nCorrect! " << (a * b) << " is the answer!" << endl << endl;
cout << "Play again (Y) or (N)?" << endl;
}
Looks like you're missing some braces. Change this block…
if (choice == 'y')
cout << "\n\n";
game();
…to this…
if (choice == 'y')
{
cout << "\n\n";
game();
}
Also, it would probably be better to change this statement…
while(choice != 'n')
{
…
}
…to this…
while(choice == 'y')
{
…
}
This way, only 'y' will be considered a confirmation. If it is the other way, anything other than 'n' will be considered a confirmation.