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.
Related
When the user inputs 'Y' to try again, the game runs but only gives the user 1 try instead of 3 tries. Program works fine the first time it runs with 3 tries. I'm guessing something is wrong with my loop that it does not reset the number of tries? Let me know if there's any other way I could write my code to make it cleaner/better. Thanks a bunch.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int guessNum;
int randomNum;
int Tries = 0;
int startGame()
{
cout << "Number: ";
cin >> guessNum;
return guessNum, Tries;
}
int main(int a, int b)
{
while (true) {
a = guessNum;
b = Tries;
char ans;
// Random number
srand(time(NULL));
randomNum = rand() % 20 + 1;
// Introduction
cout << "Guess a number between 1 to 20. You have three attempts." << endl;
do
{
startGame();
if (guessNum < randomNum)
{
cout << "Wrong! It is too low." << endl;
}
else if (guessNum > randomNum)
{
cout << "Wrong! It is too high." << endl;
}
Tries++;
}
while (guessNum != randomNum && Tries < 3);
if (guessNum != randomNum) // Wrong answer & run out of tries
{
cout << "Oops.. All attempts used. The answer is " << randomNum << endl;
}
else if (guessNum == randomNum) // User guessed correct number
{
cout << "Yes! You are correct!" << endl;
}
cout << "Try again?";
cin >> ans;
cin.ignore();
if (ans == 'N')
{
cout << "Thanks for playing!";
break;
}
}
}
EDITED V1
#include <iostream>
#include <ctime>
using namespace std;
int guessNum;
int startGame()
{
cout << "Number: ";
cin >> guessNum;
return guessNum;
}
int main()
{
while (true) {
int randomNum;
int Tries = 0;
char ans;
// Random number
srand(time(NULL));
randomNum = rand() % 20 + 1;
// Introduction
cout << endl << "Guess a number between 1 to 20. You have three attempts." << endl;
do
{
startGame();
if (guessNum < randomNum)
{
cout << "Wrong! It is too low." << endl;
}
else if (guessNum > randomNum)
{
cout << "Wrong! It is too high." << endl;
}
Tries++;
}
while (guessNum != randomNum && Tries < 3);
if (guessNum != randomNum) // Wrong answer & run out of tries
{
cout << "Oops.. All attempts used. The answer is " << randomNum << endl;
}
else if (guessNum == randomNum) // User guessed correct number
{
cout << "Yes! You are correct!" << endl;
}
cout << "Try again? Y/N: ";
cin >> ans;
cin.ignore();
ans = toupper(ans);
if (ans == 'N')
{
cout << endl << "Thanks for playing!";
break;
}
else
{
Tries = 0;
}
}
}
Actually, your program has several defects.
Firstly, If you wonder why the game behaves unexpected way after the first one, You did not set back the Tries to 0 after playing the game.
And, int startgame() should return only one variable. You are trying to return guessnum and Tries at the same time. The only reason the first game is running as expected is that you are using global variables, which is also considered as a bad practice(Some company may fire you if you use it without any good reason).
Furthermore, you are getting two int function arguments from main call, which is not valid. (main function signature should be int main(void) or int main(int argc, char* argv[])). I am surprised that the compiler did not catch this error.
And the variables (int a, int b) are actually not used. When you find unused variables, it is usually a good practice to remove them for maintainability.
So int Tries = 0; is a global variable. It's set before main().
You basically have
int Tries = 0;
main()
{
while (true) {
do
{
Tries++;
} while(Tries < 3);
}
}
Do you see that for each iteration in while, the value of Tries from the previous iteration is used? You would need to reset it before iterating again.
But there is no reason to have "Tries" as a global variable since you only need to know about it in the while(true)-loop. This is generally the case for a variable - put it to the closest scope possible:
main()
{
while (true) {
int Tries = 0;
do
{
Tries++;
} while(Tries < 3);
}
}
Now it's correctly reset between loops, and it is clear it is only needed for the loop logic.
Try to do the same for you other variables.
Try:
if (ans == 'N')
{
cout << "Thanks for playing!";
break;
}
else
{
Tries = 0;
}
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;
I am facing difficulties in my C++ code. I am a beginner. Like, only with very basic knowledge of C++. So, I really can't figure a way to do this. I thought of making an RPG game using C++ commands and am close to finishing it. But somehow, I couldn't make a constant health for the hero. Taking a look at the code,
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class player
{ public:
int health = 100;
};
int battle();
void death();
int main()
{
int abc;
player hero;
hero.health = abc;
int a;
int replay = 1;
cout << "You have 100 Hp. \n";
while (replay == 1)
{
srand(time(0));
cout << "\n Press 1 to move forward; 2 To stay. \n";
cin >> a;
if (a == 2)
{
if (rand() % 4 + 1 != 1)
{
cout << "You stay at your place. \n";
}
else
{
cout << "Enemy Attacks! (20 Hp) \n";
//battle(hero.health);
//cout << "\n Press 1 to continue. \n";
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else if (a == 1)
{
if (rand() % 2 + 1 != 1)
{
cout << "You moved forward. No one around. \n";
}
else
{
cout << "You move forward. Enemy attacks! (20 Hp) \n";
battle(abc);
cout << "\n Do you want to play again? Press 1 to replay and 0 to quit.\n";
cin >> replay;
}
}
else
{
cout << "Sorry. Please enter a valid move. \n";
}
}
return 0;
}
int battle(int x)
{
player enemy;
enemy.health = 20;
player hero;
int y;
while (enemy.health >= 0)
{
int eattack = rand() % 15 + 7;
int attack = rand() % 10 + 1;
int escape = rand() % 4 + 1;
cout << "\n Press 1 to attack. 2 to flee \n";
cin >> y;
if (y == 2)
{
if (escape != 1)
{
cout << "Can't escape! \n";
cout << "Enemy attacked! Dealing a damage of: " << eattack << " Hp. \n";
hero.health = hero.health - eattack;
cout << "Your Hp is: " << hero.health;
}
else
{
goto Aftermath;
}
}
else if (y != 1)
{
cout << "Sorry. Please enter a valid response. \n";
}
else
{
cout << "You attack the enemy. \n";
cout << "You deal a damage of: " << attack;
enemy.health = enemy.health - attack;
if (enemy.health >= 0)
{
cout << "\n Enemy attacks you, dealing: " << eattack << " Hp damage.";
hero.health = hero.health - eattack;
cout << "\n You have: " << hero.health << " Hp left.";
}
}
if ((hero.health <= 0) || (hero.health == 0))
{
death();
enemy.health = -1;
}
}
if (hero.health > 0)
{
cout << "\n Enemy fainted!";
//cout << "You found Hp Potion! Your Hp was refilled.";
}
Aftermath:
if ((hero.health > 0) && (enemy.health > 0))
{
cout << "Escaped Successfully! \n";
}
return x;
}
void death()
{
cout << "You died!";
}
As you see, I have called for battle(abc) and battle(hero.health) [which I have commented for now] but the problem is, it says "Too many arguments to function int battle(). Previously, I simply avoided parameters and created object "hero" in the battle method itself. But every time you get through a battle sequence, it comes back and declares it again, thus making its health refill. [Look at if (hero.health > 0) ]
I really don't know about global variables and all that. I just want to know if there is a workaround or a way to solve this parameter problem. Any other suggestions to have health as a 'constant' and not declared every time is also warmly accepted. Thank you so much!
P.S. Suggestions for shortening the code also accepted but please, I am a beginner. So advanced strategies are beyond my skills right now. I take time to grasp concepts.
You declare the function before the main method, and then you implement the function after the main method.
The problem is, you implement the function as:
int battle(int x)
but this doesn't match your declaration:
int battle();
Just change your function declaration block so the battle function matches the expected signature:
int battle(int x);
void death();
That will get your code compiling, but you are still a number of steps from getting this to work.
I'll give you one starter: instead of passing in the hitpoints into battle, pass the entire player.
void battle(Player &player)
{
// ...
}
Then you can modify the player's hitpoints directly in the battle function.
You would then call this with:
battle(hero);
I have an error when I try to build my program reading:
'error: 'celsius()' was not declared in this scope'
Now, correct me if I'm wrong but I think the problem is that because the function 'fahrenheit' comes before my other function 'celsius' when I call it in the fahrenheit function, it won't work. Now, it would be simple enough to switch them around but fahrenheit is also called in the celsius function.
In python, all you need to do is just globalise it with the 'global' syntax so what is the C++ equivalent?
Thanks
PS. Here is my code if you want it.
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int fahrenheit(){
system("CLS");
cout << "-----------------------------------------------";
cout << "\nYOU HAVE CHOSEN FAHRENHEIT TO CELSIUS MODE";
cout << "\n----------------------------------------------";
bool again;
again = true;
while (again == true){
int tempurf;
cout << "\nFahrenheit Temperature to be Converted: ";
cin >> tempurf;
int tempurc;
tempurc = tempurf - 32;
tempurc = tempurc * 5;
tempurc = tempurc / 9;
cout << "\n\n" << tempurf << " F is " << tempurc << " C";
cout << "\n\n\n\nWHAT WOULD YOU LIKE TO DO: ";
cout << "\n - ANOTHER CONVERSION TYPE A";
cout << "\n - FOR CELSIUS MODE TYPE C";
cout << "\n - TO EXIT TYPE E";
bool goodc;
goodc = false;
while (goodc == false){
string choosing;
cout << "\n ";
cin >> choosing;
if (choosing == "A" or choosing == "a"){
system("CLS");
goodc = true;
}
else if (choosing == "C" or choosing == "c"){
goodc = true;
again = false;
celsius();
}
else if (choosing == "E" or choosing == "e"){
goodc = true;
again = false;
return 0;
}
else{
cout << "\n Invalid Choice";
}
}
}
}
int celsius(){
system("CLS");
cout << "---------------------------------------------";
cout << "\nYOU HAVE CHOSEN CELSIUS TO FAHRENHEIT MODE";
cout << "\n---------------------------------------------";
bool again;
again = true;
while (again == true){
int tempuc;
cout << "\nCelsius Temperature to be Converted: ";
cin >> tempuc;
int tempuf;
tempuf = tempuc * 9;
tempuf = tempuf / 5;
tempuf = tempuf + 32;
cout << "\n\n" << tempuc << " C is " << tempuf << " F";
cout << "\n\n\n\nWHAT WOULD YOU LIKE TO DO: ";
cout << "\n - ANOTHER CONVERSION TYPE A";
cout << "\n - FOR FAHRENHEIT MODE TYPE F";
cout << "\n - TO EXIT TYPE E";
bool goodc;
goodc = false;
while (goodc == false){
string choosing;
cout << "\n ";
cin >> choosing;
if (choosing == "A" or choosing == "a"){
system("CLS");
goodc = true;
}
else if (choosing == "F" or choosing == "f"){
goodc = true;
again = false;
fahrenheit();
}
else if (choosing == "E" or choosing == "e"){
goodc = true;
again = false;
return 0;
}
else{
cout << "\n Invalid Choice";
}
}
}
}
int main(){
cout << "Welcome to the Fahrenheit/Celsius Converter!";
cout << "\n By Ben Sarachi";
cout << "\n\nWhich way would you like to convert to:";
cout << "\n - If you would like Fahrenheit to Celsius please type F";
cout << "\n - If you would like Celsius to Fahrenheit please type C";
// GC stands for good choice
bool gc;
gc = false;
while (gc == false){
string choice;
cout << "\n ";
cin >> choice;
//Call Functions
if (choice == "F" or choice == "f"){
gc = true;
fahrenheit();
}
else if (choice == "C" or choice == "c"){
gc = true;
celsius();
}
else{
cout << "Invalid Choice";
}
}
}
You want to add a forward declaration for your function so that the compiler knows the function exists. What's happening is that Fahrenheit is calling Celsius, but the compiler doesn't know what Celsius is at that point.
At the top of your code, add the following just below your includes:
int fahrenheit();
int celsius();
This tells the compiler that you will be defining those functions at some point.
Then you can declare your functions in any order in the file that you like.
Also, for future reference, that forward declaration should have the same signature as your function. So if you had a function like:
void foo(int bar) { ... }
then your forward declaration would be:
void foo(int);
What you need is function forward declarations. Put the following string before definition of fahrenheit function:
int celsius();
This will tell the compiler, that such a function exists and has the following prototype. But the body will be introduce at some point later.
You get the error because at the time of compiling the fahrenheit() function, celsius() is not known. You have to forward declare it.
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int celsius(); // this is the forward declaration
int fahrenheit(){
// do something
celsius();
}
int celsius(){
// implement the function
}
The alternative is you create a class and put the two functions as member of that class. You won't need forward declaration then (though declaring a class is arguably another form of that).
You have several other problems in your code:
your functions are set to return int, but not all paths return a value
what is or here choice == "F" or choice == "f"? is it #defined somewhere as ||?
do not use conditions such as gc == false or gc == true. prefer to use gc and !gc as in if(gc) or while(!gc)
Separate function declaration from definition.
Change your code to something like this:
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;
int celsius();
int fahrenheit();
int fahrenheit()
{
// ...
}
int celsius()
{
// ...
}
int main(int argc, char** argv)
{
// ...
}
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.
}