Too Many Arguments in C++ - c++

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);

Related

C++ Clases, variable is always different from the actual number

I'm trying to make a text based turn based rpg for which i wanted to have different classes with different ranges of stats. One problem I keep running into is that i cannot print the random number I obtained outside of where I get my number. If i do it just gives me a new one instead of my previous number.
Filename: Finalh.h
#pragma once
#include <iostream>
using namespace std;
// Base class
class Base {
public:
int newATK, newHP,answer,player;
int ATK, HP;
};
// Derived class
class Thief : public Base {
public:
int HP = rand() % (80 + 1 - 60) + 60;
int ATK = rand() % (40 + 1 - 20) + 20;
};
Filename: Final.cpp
#include <iostream>
#include "Finalh.h"
using namespace std;
int main()
{
srand(static_cast<unsigned>(time(NULL)));
int answer;
cout << "Choose your fighter 1) Assassin 2) Tank 3) Knight" << endl;
cin >> answer;
if (answer == 1)
{
Thief player;
cout << "You have choosen assassin, he has HP " << player.HP << " and ATK " << player.ATK
<< endl;
player.newHP = player.HP;
}
cout << "Press 1 to show HP" << endl;
cin >> answer;
if (answer == 1)
{
Thief player;
cout << "This is my HP " << player.HP << endl;
cout << "This is my HP " << player.newHP << endl;
}
}```
drescherjm was right, the value got lost due to the instance life running out the moment I closed the if. The solution was just passing the value to a variable and then printing that variable:
newHP = player.HP;
newATK = player.ATK;
cout << "You have choosen assassin, he has HP " << newHP << " and ATK " << newATK << endl;

Can someone help me figure out why my code isn't working properly?

#include <iostream>
using namespace std;
int fight();
int lowblow();
int eyes();
int run();
int underground();
int officebuilding();
int main()
{
int choice1;
int fchoice2, fchoice3;
int rchoice2, rchoice3;
cout << "As you’re walking down the street you feel somebody grab your shoulder, when you turn around to see. You notice the person is holding a knife towards you and demanding for your valuables." << endl;
cout << "Do you fight or run?" << endl;
cout << "1 - Fight" << endl;
cout << "2 - Run" << endl;
cin >> choice1;
while (choice1 != 1 && choice1 != 2) {
cout << "Do you fight or run? " << endl;
cout << "1 - Fight" << endl;
cout << "2 - Run" << endl;
cin >> choice1;
}
if (choice1 == 1) {
fchoice2 = fight();
while (fchoice2 != 1 && fchoice2 != 2) {
fchoice2 = fight();
}
if (fchoice2 == 1) {
fchoice3 = lowblow();
while (fchoice3 != 1 && fchoice3 != 2) {
fchoice3 = lowblow();
}
}
if (fchoice2 == 2) {
fchoice3 = eyes();
while (fchoice3 != 1 && fchoice3 != 2) {
fchoice3 = eyes();
}
if (choice1 == 2) {
rchoice2 = run();
while (rchoice2 != 1 && rchoice2 != 2) {
rchoice2 = run();
}
if (rchoice2 == 1) {
rchoice3 = underground();
while (rchoice3 != 1 && rchoice3 != 2) {
rchoice3 = underground();
}
if (rchoice3 == 1) {
officebuilding();
}
}
}
}
}
}
int fight()
{
system("clear");
int c2;
cout << "You choose to fight off the attacker and suddenly all those self-defense classes come rushing into your mind.As you fight to defend yourself, you find yourself getting outmatched and have to try something drastic to survive." << endl;
cout << "1 - Go for the low blow" << endl;
cout << "2 - Go for the eyes " << endl;
cin >> c2;
return c2;
}
int lowblow()
{
system("clear");
cout << "You catch your attacker off guard and land the hit, to your surprise the attack proves ineffective.In retaliation you get hit so hard that you start seeing stars and soon blackout leaves you defenseless.Now you are knocked out and getting your valuables taken." < endl;
cout << "The End" << endl;
return 0;
}
int eyes()
{
system("clear");
cout << "Using the element of surprise to try fighting back gave you no advantage, so you resort to another tactic. You’ve seen it in movies and it always worked out there. You decide to go for the eyes and to your surprise it works. You use this opportunity to escape and get to safety, all while keeping your valuables safe. "<< endl;
cout << "The End" << endl;
return 0;
}
int run()
{
system("clear");
int c2;
cout << " While running down the street to loose the attacker, you noticed that there was an underground subway a little down the road.Immediately to your left there is an office building you could run into and try to lose your attacker there."<< endl;
cout << "1 - Underground ?" << endl;
cout << "2- office building?" << endl;
cin >> c2;
return c2;
}
int underground()
{
system("clear");
cout << "As you make your way towards the underground subway station you notice rushing out.In a desperate attempt to reach safety, you run down the stairs while narrowly avoiding others.Upon arriving at the station you look back and notice that you lost your attacker.You are safe now.";
cout << "The End" << endl;
return 0;
}
int officebuilding()
{
system("clear");
cout << "A spontaneous decision leads you into an office building, while it may look safe, upon entering you notice everything is silent as the building seems to be completely empty.None of it matters however, since you have to escape at any cost in order.While trying to find a good way to lose the attacker you hear footsteps behind you.The attacker has cornered you and has taken your valuables." << endl;
cout << "The End" << endl;
return 0;
}
I am suppose to be writing a branching-path story. I am not sure why after I pick a choice it starts flashing and for the other choice it isn't even working. I'm not exactly sure where to fix these errors in the code. I'm not sure if I messed up somewhere in the functions or while loop. I've tried changing some things around but nothing seems to work.
You are calling underground() in a while-loop waiting for rchoice3 to be 1 or 2, but underground() always returns 0, so rchoice3 is always 0..
while (rchoice3 != 1 && rchoice3 != 2) {
rchoice3 = underground();
}
I think you need to change this block:
if (rchoice2 == 1) {
rchoice3 = underground();
while (rchoice3 != 1 && rchoice3 != 2) {
rchoice3 = underground();
}
if (rchoice3 == 1) {
officebuilding();
}
}
To:
if (rchoice2 == 1) {
underground();
} else {
officebuilding();
}

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');
}
}

Need help understanding " rand() % 67 < 10"

I am trying to practice my C++ in order to grasp a better understanding in class, as I am a beginner and a little behind, and I came across a zombie game that someone posted online.
Anyways, I understand most of the code, however I do not understand "if(rand() & 67 < 10)".
I can interpret "rand() % 10 + 1", in which the code will generate a number, or in this case zombies, between 1 and 10.
Thinking at first that the zombies would cap at 67, given the player had chosen a high number, but I don't believe that is its function, but again, I'm not entirely sure...
Here is an example of the code I am looking at:
I'm sure its something simple, however I am still confused on its purpose. Even after trying to learn its function my running the game
Here is the whole code just in case:
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
using namespace std;
int createZombie() { // createZombie function OPEN
if(rand() % 67 < 10)
return 11;
else
return rand() % 10 + 1;
} // createZombie fuction CLOSED
// #################### MAIN FUNCTION ############################
int main() { // main function OPEN
srand(time(NULL));
char enter;
// game stats
int playerAlive = true;
int playerSkill = 9;
int playerScore = 1;
string playerName = "";
int zombieCount = 0;
int zombiesKILLed = 0;
// title
cout << "Welcome to Zombie War." << endl << "Press [ENTER] to start ";
cin.get();
// player name
cout << "Please enter your name: ";
cin >> playerName;
// ask how many zombies
cout << "How many zombies do you wish to fight? ";
cin >> zombieCount;
cout <<"Get ready to fight for you life, " << playerName << "!" << endl;
// main game loop
while(playerAlive && zombiesKILLed < zombieCount) { // while loop OPEN
// create a random zombie
int zombieSkill = createZombie();
// battle sequence
if(zombieSkill > 10) { // if statment OPEN
cout << endl << "Here comes a huge zombie! " << endl;
} // if statement CLOSED
else { // else statement OPEN
cout << endl << "Here comes Zombie " << zombiesKILLed + 1 << endl;
} // else statement CLOSED
cout << "Fighting... " << endl;
sleep(2);
// zombies killed the player
if(playerSkill < zombieSkill) { // if statement OPEN
playerAlive = false;
cout << "You have died." << endl;
} // if statement CLOSED
else { // else statment OPEN
// PLAYER KILLED THE ZOMBIE
if(playerSkill - zombieSkill > 7) { // if statement OPEN
cout << "You wasted the Zombie! " << endl;
playerScore = playerScore * 2;
} // if statment CLOSED
else if (playerSkill - zombieSkill > 5) { // else if statement OPEN
cout << "You decapitated the Zombie!" << endl;
playerScore = playerScore * 2;
} // else if statement CLOSED
else if (playerSkill - zombieSkill > 0) { // else
if statement OPEN
cout << "You Killed the Zombie!" << endl;
playerScore = playerScore * 2;
} // else if statment CLOSED
else { // else statment OPEN
cout << "You killed the zombie, but suffered injuries." << endl;
} // else statment CLOSED
zombiesKILLed++;
} // else statment CLOSE
cout << endl;
sleep(1);
} // while loop CLOSED
if(zombiesKILLed == zombieCount) { // if statement OPEN
// victory
cout <<"Your have survived the onslaught!" << endl;
} // if statement CLOSED
else { // else statement OPEN
// LOST
cout << "You did not survive the zombie war" << endl;
} // else statement CLOSED
cout << "Zombies killed: " << zombiesKILLed << endl;
cout << "Final score: " << playerScore << endl << endl;
} // main function CLOSED
Splitting the command into two parts for easy understanding:
Part I-
rand() % 67
= generate any random number from 0-66
= remainder of division of any number by 67
= N (say)
Part II
if( rand() % 67 < 10)
= if( N < 10)

Redefiniton of an int error

I'm teaching my self C++ on the side and i realize this question may seem remedial to some. In the game I'm making as part of the learning process I want the user to be able to pick a difficulty and when they pick one or the other the random number value range changes. The compiler I'm using is x-Code by the way. Here is the code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int secretNumber;
int main() //integrate difficulty chooser where easy is a number b/w 1 and 10, norm 1 and 50, and hard is 1 and 100
{
srand(static_cast<unsigned int>(time(0))); //seeds random number by time read on system
int guess;
int choice;
char again = 'y';
cout << "\tWelcome to Guess My Number\n\n";
cout << "Please choose a difficulty:\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n";
cin >> choice;
while (again =='y')
{
int tries = 0;
int secretNumber;
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
int secretNumber = rand() % 10 + 1;
break;
case 2:
cout << "You picked Normal.\n";
int secretNumber = rand() % 50 + 1;
break;
case 3:
cout << "You picked Hard.\n";
int secretNumber = rand() % 100 + 1;
break;
default:
cout << "You have made an illegal choice.\n";
}
if (guess > secretNumber)
{
cout << "\nToo high!";
}
else if (guess < secretNumber)
{
cout << "\nToo low!";
}
else if (guess == secretNumber && tries == 1)
{
cout << "\nThat's unbelievable! You guessed it in exactly 1 guess";
}
else
{
cout << "\nGreat job, you got it in just " << tries << " guesses!\n";
}
}
while(guess != secretNumber);
cout << "Do you want to play again y/n: ";
cin >> again;
}
return 0;
}
The 2 errors occur in case 2 and 3 where i try to redefine the value of secretNumber.
The case blocks do not open different scopes, but are rather part of the same block. Your code (considering only scopes) looks somehow similar to:
int secretNumber;
{
int secretNumber = rand() % 10 + 1;
...
int secretNumber = rand() % 50 + 1;
...
int secretNumber = rand() % 100 + 1;
}
Three different variables with the same name are being declared in the same scope, which is not allowed in the language. Note that all three declarations inside the switch would also hide the variable declared in the outer scope, which is probably not what you want anyway.
It looks like you have some background in some other languages - perhaps a functional language and perhaps some JavaScript.
One of the key features of C++ is scoping. Variables (named value holders) have a lifetime of the scope they are within, and variables are only visible within the scope they are defined. (Not to be confused with objects, which through pointers and allocation can be teased off the stack and into heap memory, only to be lost when the variables with their address go out of scope if they are not properly deallocated).
{
int i = 1;
}
std::cout << "i is " << i << std::endl; // compiler error, i does not exist here.
void foo() {
int i = 1;
}
void bar() {
foo();
std::cout << i << std::endl; // compiler error, i does not exist here.
}
Also, unless decorated as "const", C++ variables are mutable - they can be changed.
int i = 1;
i = 2;
std::cout << i << std::endl; // writes 2, not 1.
So: your code is not 'redefining' secretNumber, it is shadowing the previous definition, hiding it for the duration of the current scope. Thus when you assign a value to the inner version, the "secretNumber" visible to code outside the scope is untouched.
#include <iostream>
int main()
{
int foo = 1; // outer foo
std::cout << "Originally, foo = " << foo << std::endl;
{
int foo = 2; // inner foo
std::cout << "Inside the inner scope, foo = " << foo << std::endl;
}
// inner foo doesn't exist here, so it references outer foo.
std::cout << "But the original foo still exists, " << foo << std::endl;
}
What you actually want to do is simply assign a new value to the original secretNumber variable you declared in the outer scope, since that is the only variable named "secretNumber" available to code in that scope.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int secretNumber;
int main() //integrate difficulty chooser where easy is a number b/w 1 and 10, norm 1 and 50, and hard is 1 and 100
{
srand(static_cast<unsigned int>(time(0))); //seeds random number by time read on system
int guess;
int choice;
char again = 'y';
cout << "\tWelcome to Guess My Number\n\n";
cout << "Please choose a difficulty:\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n";
cin >> choice;
while (again =='y')
{
int tries = 0;
int secretNumber;
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
secretNumber = rand() % 10 + 1;
break;
case 2:
cout << "You picked Normal.\n";
secretNumber = rand() % 50 + 1;
break;
case 3:
cout << "You picked Hard.\n";
secretNumber = rand() % 100 + 1;
break;
default:
cout << "You have made an illegal choice.\n";
}
if (guess > secretNumber)
{
cout << "\nToo high!";
}
else if (guess < secretNumber)
{
cout << "\nToo low!";
}
else if (guess == secretNumber && tries == 1)
{
cout << "\nThat's unbelievable! You guessed it in exactly 1 guess";
}
else
{
cout << "\nGreat job, you got it in just " << tries << " guesses!\n";
}
}
while(guess != secretNumber);
cout << "Do you want to play again y/n: ";
cin >> again;
}
return 0;
}
This is one reason why many C++ programmers choose to use prefix and suffix notations to distinguish certain types of variables:
#include <iostream>
class Foo {
public:
int m_i; // member variable, m_xxx
Foo(int); // constructor taking an int.
};
static int s_i;
Foo::Foo(int i_) // arguments use _ suffix
{
int i = i_; // local value of i
i *= 3;
m_i = i; // we're assigning it the local value, not the argument.
}
int main()
{
int i = 1;
Foo foo(2);
s_i = 3;
std::cout << "i = "<<i<<", foo.m_i = "<<foo.m_i<<", s_i = "<<s_i<< std::endl;
}
Live Demo: http://ideone.com/dSTwPT
You are getting the compile time error because you are redeclaring the same variable within the same scope (case statement block level scope). You need to delete int before secretNumber in all the case statements. Doing otherwise, the secretNumber variable declared at the while loop block level will stay undefined.