C++ game returns 0 automatically [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Whenever i try to run this game, it automatically returns 0.
The game is a text-based survival game that i coded on Code::Blocks. The compiler is MinGW. I am a semi-knowledgeable programmer. There is no error when compiled.
// This game automatically returns 0 and ends for some reason...
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int hunger;
int warmth;
int thirst;
int choice;
// Declares variables for hunger, warmth, thirst, and the users choice
int start()
{
cout<< "You are stuck in a forest, all alone"<< endl;
cout<< "You must maintain your hunger, thirst, and warmth." << endl;
int mainPage();
}
int hunt()
{
srand(time(0));
cout<< "You have chosen hunt!"<< endl;
if ((rand() % 2) == 2){
cout<< "You caught a deer!"<< endl;
hunger = hunger + 1;
}
else{
cout<< "You could not find anything..."<< endl;
}
int mainPage();
}
// The previous function is used for the hunting choice
int wood()
{
cout<< "You have chosen find firewood!"<< endl;
if ((rand() % 2) == 2){
cout<< "You found firewood!"<<endl;
warmth = warmth + 1;
}
else{
cout<< "You could not find any firewood"<< endl;
}
int mainPage();
}
// Wood choice
int water()
{
cout<< "You have chosen find water!"<< endl;
if ((rand() % 2) == 2){
cout<< "You have found a river!"<< endl;
thirst = thirst + 1;
}
else{
cout<< "You could not find anything..."<< endl;
}
int mainPage();
}
// Water choice
int mainPage()
{
warmth = warmth - 1;
hunger = hunger - 1;
thirst = thirst - 1;
// Subtracts one from each variable per turn
if (hunger == 0){
cout<< "You starved!"<< endl;
cout<< "Game over!"<< endl;
return 0;
}
if (thirst == 0){
cout<< "You became dehydrated!"<< endl;
cout<< "Game over!"<< endl;
return 0;
}
if (warmth == 0){
cout<< "You froze!"<< endl;
cout<< "Game over!"<< endl;
return 0;
}
// You die if any of the variables reach zero
cout<< "Your hunger is"<< hunger<< endl;
cout<< "Your warmth is"<< warmth<< endl;
cout<< "Your thirst is"<< thirst<< endl;
cout<< "What would you like to do?"<< endl;
cout<< "1 = hunt, 2 = find firewood, 3 = find water"<< endl;
cin>> choice;
if (choice = 1){
int hunt();
}
if (choice = 2){
int wood();
}
if (choice = 3){
int water();
}
// The main page that takes the users choice as input and also tells you the amount of each variable
}
int main()
{
hunger = 5;
thirst = 5;
warmth = 5;
int start();
}
// the main function

You have several issues with you code. First you are not calling your function correctly. When you have
int start();
in main() it doesn't call the start function but instead declares a function named start that returns an int and takes nothing. Knowing that you main function essential becomes
int main() {}
since you do nothing except set some variables that will never be used. A good compiler with a warnings turned on should have at least told you that you had unused variables.
You are going to have this same issue everywhere else you call a function as you declare a function instead of calling it.
Your second issue will come up after you fix your function calls. You will be using functions before you have defined them. A easy way to fix this is to declare the function prototype of all of your functions before you define/use any of them so the compiler knows that the function is going to exist.
A third issue is you use
srand(time(0));
in the function hunt(). This means that every time you call hunt you will reseed rand. instead of doing that you can put srand(time(0)); in main and then you will only seed rand once per execution of the program.
One last thing I see is none of your functions that are declared to return an int actually return anything. If you declare that a function has a return value then you need to return something from the function. If you do not want to return anything then you can make the return type void which means the function returns nothing.

Related

C++ need help, random switch statements [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm writing a code which is kind of like a fortune teller but I'm having some trouble with my switch statements. When executed the code prints out the same message and doesn't pick a random case like its supposed to! can someone please help me! thank you!
heres my code
#include<iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
void printGreeting(); // function prototype
int main()
{
int choice;
printGreeting();
cout << "Would you like to see your fortune?" << endl;
cout << "Press 1 to see your fortune or 2 if you don't!" << endl;
cin >> choice;
if (choice == 1)
{
cout << "Great! Your fortune is: ";
// Function to generate random number
void rand1();
srand(time(NULL));
int MAX_NUM;
MAX_NUM = 5;
int random = rand() % MAX_NUM;
cout << random << endl;
int selection;
selection = 5;
switch (selection)
{
case 1:
cout << "Change can hurt, but it leads a path to something better!";
break;
case 2:
cout << "If you have something good in your life don't let it go!";
break;
case 3:
cout << "You're in for a treat today.";
break;
case 4:
cout << "Land is always on the mind of a flying bird";
break;
case 5:
cout << "A dream you have will come true";
break;
}
return 0;
}
else if (choice == 2)
{
cout << "Okay goodbye!" << endl;
}
}
// Prints greeting message
void printGreeting() // function header
{
cout << "Hello! Welcome to your fortune teller!" << endl; // function body
}
Because selection = 5;
You want to choose selection with a random value between 1 - 5, right?
You switch by selection variable, which is explicitly set to 5 right before the switch itself. Consider switching by random variable.

Function running twice in console [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Basically, whenever I run this program in console to test it, my Menu() function gets called and when I give input, it prints the whole Menu() function again. Please help me fix this.
p.s. This is incomplete.
#include <iostream>
#include <windows.h>
using namespace std;
int Menu();
int main()
{
float currMoney = 0;
float giveMoney = 0;
float coke = 8.50;
float fantaG = 9;
float fantaO = 9;
float creamS = 7;
Menu();
int Choice = Menu();
system("cls");
if(Choice == 1)
{
cout<< "Insert R"<< coke << endl;
int pay = 0;
cin>> pay;
float returnA = pay - coke;
if(returnA < 0)
{
returnA = -returnA;
cout<< "you still owe R"<< returnA << "0" << endl;
}
}
}
int Menu()
{
cout<< "[Drink machine v1.0]\n\n"<< endl;
cout<< "[1]Coke -- R8,50"<< endl;
cout<< "[2]Fanta grape -- R9,00" <<endl;
cout<< "[3]Fanta orange -- R9,00"<< endl;
cout<< "[4]Cream Soda -- R7,00"<< endl;
int Choice = 0;
cin>> Choice;
return Choice;
}
The reason it's being called twice is because you're calling it twice!
Menu(); // first time
int Choice = Menu(); // second time
In the first call you don't capture the return value - so all it does it show the menu, ask for input, and then discard the result.
In the second call you show the menu again, ask for input, and then this time you capture the result, and action on that result.
From the look of it you want to remove the first call to Menu()
You are calling it twice in the code
int main() {
Menu();
int Choice = Menu();
}

Random number generator for C++ popping up with an error?

I am having trouble with my number generator. Syntax wise, everything is working properly. I mainly wanted to use functions to see if they would work properly. When I run the program, a message pops up and says that my variable "guess" is not initialized. Can anyone give insight as to why this may be happening?
Also note that even though I didn't include my libraries in the code below, they are present in the actual program itself.
using namespace std;
int game();
string playAgain();
int main(){
game();
playAgain();
return 0;
}
int game(){
int guess;
int guessesTaken = 0;
int number = rand() % 10 + 1;
int count = 0;
cout << "I am thinking of a number between 1 and 10, can you guess it? " << endl;
while (guessesTaken < count){
cout << "Take a guess: " << endl;
cin >> guess;
if (guess > number)
cout << "Too High. Try again!" << endl;
if (guess < number)
cout << "Too Low! Try again!" << endl;
if (guess == number)
break;
}count++;
if (guess == number)
cout << "Congratulations!" << endl;
return 0;
}
string playAgain(){
string play;
cout << "Want to play again?: " << endl;
if (play == "y" || "Y")
main();
else
cout << "Thanks for playin" << endl;
return 0;
}
It happens because you did not initialise guess, precisely as the warning says.
Sure, if you assume that the cin >> guess operation will always succeed, then initialisation becomes largely irrelevant as the variable will take on a deterministic value.
But:
the compiler does not know this when it warns you, and
you have no error checking on your cin >> guess operation; not only can you not assume that it will always succeed, but your program has no clue whether it actually did.
Furthermore, the entire loop may not be executed at all if your other variables have the right values, so the compiler is completely right in its observation.
Initialise your variables and put error checking around your stream operations.
Furthermore, that count++ should obviously be in the loop body, and your loop otherwise needs refactoring in general because it begins with the 0 < 0 case. You should think hard about what you intend the semantics of your program to be.

Cannot exit while loop with boolean condition c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Hi this is my first post. I apologize if I'm not following certain rules or conventions. If that is the case please let me know.
I have a game which runs in a while loop until the score limit is reached by either player, at which point the other player has one last (iteration) chance to beat the first players score. However after the score limit is reached, the loop continues to run and the winner is never checked.
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
using namespace std;
int roll();
int playTurn(int);
int main(){
const int LIMIT = 5;
int whoseTurn = 1;
int pnts1 = 0;
int pnts2 = 0;
bool suddenDeath = false; //True when score limit is reached
while(!suddenDeath){
if(pnts1 >= LIMIT || pnts2 >= LIMIT){ //Limit was reached by previous player.
suddenDeath == true; //Next player has 1 turn to win
}
if(whoseTurn == 1){
pnts1 += playTurn(whoseTurn); //Play turn and tally points
whoseTurn = 2; //Swith player for next iteration
}
else if(whoseTurn == 2){
pnts2 += playTurn(whoseTurn);
whoseTurn = 1;
}
cout << "-------------------------------------" << endl //Display score
<< "Player 1 has " << pnts1 << " points" << endl
<< "Player 2 has " << pnts2 << " points" << endl
<< "-------------------------------------" << endl << endl;
};
if(pnts1 > pnts2)
cout << "Congratulations Player 1! You won with a score of: " << pnts1 << " - " << pnts2;
else if(pnts2 > pnts1)
cout << "Congratulations Player 2! You won with a score of: " << pnts2 << " - " << pnts1;
else if(pnts1 == pnts2)
cout << "A tie! What are the chances?";
return 0;
}
suddenDeath == true;
// ^^
is an expression meaning "compare those two values", which is then thrown away. The C statement 42; is equally valid, and equally useless (a).
You want to assign the value, so you'd use:
suddenDeath = true;
// ^
It's actually the other end of the much more common if (a = 0) problem where people assign rather than compare.
(a) If you're wondering why anyone in their right mind would allow this into a language, it actually allows for some powerful constructs with minimal code.
And, you've seen it before most likely. The statement i++; is such a beast. It's an expression giving i (which you throw away here) with the side effect that i is incremented afterwards.
suddenDeath = true;
Use a single = for assignment. == is used for condition check.

Is this C++ Guessing Game syntactically correct?

#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int min = 1;
int max = 100;
int count = 0;
int randomint = min + (rand() % (int)(max - min + 1));
bool isCorrect = true;
while(!isCorrect){
int guess = 0;
cout << "What is your guess? " << endl;
cin >> guess;
if(guess < randomint){
cout << "Too low!" << endl;
count++;
} else if (guess > randomint){
cout << "Too high!" << endl;
count++;
} else{
cout << "Correct!" << endl;
cout << "Number of Guesses: " << count << endl;
isCorrect = true;
}
}
}
New C++ Programming. I couldn't get this to compile one IDEOne because it doesn't have the input system I need to work this program. I have to submit this for a class shortly, but given that my larger disk (where all my software was stored) was corrupted last night.
I apologize for the silliness of this question.
Yes, it is syntactically correct, but not logically, due to
bool isCorrect = true;
which prevents loop from starting, it should be
bool isCorrect = false;
and works like a charm (but it would be reasonable to initialize the random number generator by for example running srand(time(NULL));)
There are two things logically wrong in your program:
The game won't run at all, since isCorrect is initially true.
The random number generator doesn't get a seed, so rand() will return the same value on every run and randomint is always the same. You should call srand( seed ) beforehand, where seed is a unsigned (for example time(0)).*
*actually, your game will still run if you don't do this, but it's easy to beat after the first try