Infinite loop and i dont know why - c++

I am working on a school lab and i cant seem to figure out why the code keeps going in to a infinite loop. I know something is wrong with the while statement but i cant see what it is.
#include <iostream>
using namespace std;
int main()
{
int c = 0, p = 0, prof;
cout << "Do you like Coke or Pepsi? " << endl;
cin >> prof;
//put in data validation
while (prof != 'q' && prof != 'Q')
{
if (prof == 'p')
p++;
else if (prof == 'c')
c++;
cout << "Do you like Coke or Pepsi? " << endl;
cin >> prof;
}
if (p > c)
cout << "Pepsi Wins";
else if (p < c)
cout << "Coke Wins";
else
cout << " It's a tie";
system("Pause");
}

Simply the variable prof should be a char not int
char prof;

Related

calling function on while loop

I'm making a calculator program but I already encounter a problem. Well, my code is in a loop that will call a function to display the choices and then ask the user to pick, a/s/m/d are the choices. If the input is on the choices, it will proceed to the next step. Otherwise, it will loop and then call the function again.
#include <iostream>
using namespace std;
void home()
{
cout << "\nChoose your operation:" << endl;
cout << "\tType [A] for Addition" << endl;
cout << "\tType [S] for Subtraction"<< endl;
cout << "\tType [M] for Multiplication" << endl;
cout << "\tType [D] for Division" << endl;
}
int main()
{
char operation;
bool no_operator = true;
int design = 73;
for (int i = 0; i < design; i++){
if (i == 25){
cout << " WELCOME TO CALCULATOR ";
i += 22;
}
else i == 72 ? cout << "*\n" : cout << "*";
}
while (no_operator){
home();
cout << "\nOperation: ";
cin >> operation;
if (operation == 'A' || operation == 'a')
{
cout << "\nIt will going to add numbers";
no_operator = false;
}
else if (operation == 'S' || operation == 's')
{
no_operator = false;
cout << "\nIt will going to subtract numbers";
}
else if (operation == 'M' || operation == 'm')
{
no_operator = false;
cout << "\nIt will going to multiply numbers";
}
else if (operation == 'D' || operation == 'd')
{
no_operator = false;
cout << "\nIt will going to divide numbers";
}
else
{
cout << "\tInvalid Input: You must enter A/S/M/D only\n";
//home();
}
}
return 0;
}
My problem is it will run the '''home()''' in else statement even if the input is correct on the second loop.
I want to stop the '''home()''' to be called when the input is correct
Your code works perfectly fine. Make sure you're inputting the correct letters.
Also for this code, a "do while()" loop would be better.
You program is working perfectly fine as the input is correct it does not show the home rather print the message it will going to divide etc.

c++ compiler ignoring first if statement

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.
}

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.

C++ Program with pointers not working

I am a beginner and am stuck. I have written this and so far it is not working. After "Add or Remove Trader" it does nothing. Any help or tidbits on how to make this functional would be greatly appreciated. Thank you.
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
struct Department{
string deptName;
int numTraders;
};
void addTraders(Department *, int );
void removeTraders(Department *, int);
int main(){
char addOrRemove;
Department departments[10] = {
{"Bank Loan", 10},
{"Conservative Allocation", 9},
{"Europe Stock", 10},
{"Domestic", 21},
{"Asia", 10},
{"Large Growth", 5},
{"Long-term Bond", 5},
{"Money Market", 25},
{"Emerging Market", 18},
{"Large Blend", 12}
};
int choice, numberToAdd, numberToRemove;
Department* p_departments = departments;
for(int i = 0; i < 10; i++){
cout << "Department # " << (i + 1) << ", Name: " << p_departments[i].deptName <<
", Traders: " << p_departments[i].numTraders << endl;
}
cout << endl;
do{
cout << "Enter 0 to quit, or choose a department number: ";
cin >> choice;
cout << "Add or remove traders (A or R) ? ";
cin >> addOrRemove;
if(addOrRemove == 'A' || 'a'){
cout << "how many traders to add" << endl;
cin >> numberToAdd;
addTraders(&departments[choice-1] ,numberToAdd);
}
else if(addOrRemove == 'R' || 'r'){
cout << "how many traders to remove" << endl;
cin >> numberToRemove;
removeTraders(&departments[choice-1],numberToRemove);
}
else{
cout << addOrRemove << " is not a valid selection. \n";
}
for(int i = 0; i < 10; i++){
cout << "Department # " << (i + 1) << ", Name: " << p_departments[i].deptName <<
", Traders: " << p_departments[i].numTraders << endl;
}
cout << endl;
}while(count != 0);
system("pause");
return 0;
}
void addTraders(Department *dept, int numAdd){
dept->numTraders += numAdd;
}
void removeTraders(Department *dept, int numRemove){
dept->numTraders += numRemove;
}
The following condition is always evaluated as true; even if it's false || 'a', 'a' ~> true:
if(addOrRemove == 'A' || 'a'){ ...
it was meant to be:
if(addOrRemove == 'A' || addOrRemove == 'a'){ ...
However when addOrRemove is declared as a char, then:
cin >> addOrRemove;
might just read a new-line character or some white space. It would be probably more reasonable to declare addOrRemove as std::string and change your condition to:
if(addOrRemove == "A" || addOrRemove == "a"){ ...
And after you read choice and it's 0, you should break your loop so that it won't try to access element at index 0 - 1:
cin >> choice;
if (choice == 0) break; // <-- THIS
First of all instead of
if(addOrRemove == 'A' || 'a'){
you should write
if(addOrRemove == 'A' || addOrRemove == 'a'){
And secondly you should define variable count because it seems that the compiler thinks that count - is name of standard algorithm std::count.

Logic error, assistance required

I am encountering a logical error with this app. It is a word jumble app that displays a jumbled word and asks the player if he/she would like to play again once they guess correctly.
When I tell the app I do not want to play again it continues through the sequence anyway. I have a feeling that its bad nesting on my part.
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
enum fields {WORD, HINT, NUM_FIELDS};
const int NUM_WORDS = 5;
const string WORDS[NUM_WORDS][NUM_FIELDS] =
{
{"wall", "Are you banging your head against something?"},
{"jumble", "Its what this game is all about."},
{"glasses", "You might need these to read this text."},
{"labored", "Going slowly, is it?"},
{"persistent", "Keep at it."},
};
srand(static_cast<unsigned int>(time(0)));
cout << "\t\tWelcome to Word Jumble!\n\n";
cout << "Unscramble the the letters to make the word!\n";
cout << "Enter 'hint' for a hint\n";
cout << "Enter 'quit' to quit the game\n\n";
const int MAX_LEVEL = NUM_WORDS - 1;
int totalScore = 0;
for (int level = 0; level <= MAX_LEVEL; ++level)
{
string theWord = WORDS[level][WORD]; // Word to guess
string theHint = WORDS[level][HINT]; // Word hint
char playAgain;
string jumble = theWord; //Jumbled version of the word
int length = jumble.size();
int score = jumble.size() * 10;
for (int i = 0; i < length; ++i)
{
int index1 = (rand() % length);
int index2 = (rand() % length);
char temp = jumble[index1];
jumble[index1] = jumble[index2];
jumble[index2] = temp;
}
cout << jumble << endl;
string guess;
cout << "\nYour Guess: ";
cin >> guess;
while ((guess != theWord) && (guess != "quit"))
{
if (guess == "hint")
{
cout << theHint;
score = score / 2;
}
else
{
cout << "\n\nSorry thats not it.\n\n";
}
cout << "\n\nYour Guess: \n\n";
cin >> guess;
}
if (guess == theWord)
{
cout << "Thats it! You guessed it!\tYou scored: " << score << "\n\n";
cout << "Would you like to play again? (y/n): ";
cin >> playAgain;
if (playAgain = 'y')
{
continue;
}
else if (playAgain = 'n')
{
cout << "Your total score is: " << totalScore << endl;
break;
}
}
else if (guess == "quit")
{
if (totalScore > 0)
{
cout << "Your total score is: " << totalScore << endl;
}
break;
}
}
cout << "\nGoodbye.";
return 0;
}
When comparing playAgain to 'y' and 'n', you only have one equals sign, causing the first one ('y') to always execute instead of it being an actual choice, since the value of 'y' is not 0.
To fix this, they should be:
if (playAgain == 'y') //note ==
{
continue;
}
else if (playAgain == 'n') //note ==
{
cout << "Your total score is: " << totalScore << endl;
break;
}
Also, any sane (more modern) compiler should warn you about this if you have warnings turned on. Be sure to turn those on and take heed of them.
I think you will need == for your playAgain question. I often make mistakes with that.