For loop not running under a void - fight scenario - c++

I'm new to C++ and I am having some trouble with an assignment. Here is my program so far:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void fight(string heroName, int arrowCount, int enemyCount);
int main(int argc, char** argv) {
string heroName = "Legolas";
int arrowCount = 3;
int enemyCount = 3;
cout << "Welcome to the Arena, the battle will begin shortly." << endl;
system("pause");
cout << "\nToday's competitors: " << "\n" << heroName << "\n" << "3 Orcs" << endl;
system("pause");
cout << "\n" << heroName << " will be given 3 arrows" << "\n" << "3 Orcs will be given daggers. \n";
system("pause");
cout << "\nThe battle begins in...\n 3...\n 2...\n 1..." << endl;
system("pause");
fight(heroName, arrowCount, enemyCount);
}
void fight(string heroName, int arrowCount, int enemyCount) {
for (int x = arrowCount; x <= 0; x--) {
if (arrowCount == 3) {
cout << "\n" << heroName << " fires arrow at Azog." << "\nAzog has fallen due to lobotomy by arrow." << "\nLegolas notices he has 2 arrows remaining." << endl;
system("pause");
}
if (arrowCount == 2) {
cout << "\n" << heroName << " fires arrow at Dular." << "\nDular has taken an arrow to the knee and is now longer an adventurer." << "\nLegolas notices he has 1 arrow remaining." << endl;
system("pause");
}
if (arrowCount == 1) {
cout << "\n" << heroName << " fires arrow at Nagrub." << "\nNagrub has lost his testicles." << "\nLegolas notices he is out of Arrows." << endl;
system("pause");
}
}
}
The issue that I'm having is it seems that the for loop isn't initializing. Everything runs fine up to the "void fight" part of the program. How can I correct this?

Did you mean for (int x = arrowCount; x >= 0; x--) {? Note that the for loop conditional check is evaluated before the loop body is ran.
Currently your loop will terminate if x is positive, which judging from your variable name, is most likely to be the case.
Also note that the body of the for loop depends on neither x, nor enemyCount, which seems odd.

Related

how this recursion is reaching the cout statement ?

I have this function to solve the Tower of Hanoi problem and fortunately It's working good but can anybody explain to me if the function is calling it self before the cout statement in case m!=0 then how does it ever reach the cout statement or even the other call of itself ??
#include <iostream>
using namespace std;
void Hanoi(int m, char a, char b, char c){
if(m == 1){
cout << "Move disc " << m << " from " << a << " to " << c << endl;
}else{
Hanoi(m-1, a,c,b);
cout << "Move disc " << m << " from " << a << " to " << c << endl;
Hanoi(m-1,b,a,c);
}
}
int main(){
int discs;
cout << "Enter the number of discs: " << endl;
cin >> discs;
Hanoi(discs, 'A', 'B', 'C');
return 0;
}
Calling Hanoi(m), where m > 1: First it executes Hanoi(m-1) and all resulting calls. Then it executes cout. Then it executes Hanoi(m-1) and all resulting calls a second time.
Consider m == 3:
Hanoi(3)
Hanoi(2)
Hanoi(1)
cout
cout
Hanoi(1)
cout
cout
Hanoi(2)
Hanoi(1)
cout
cout
Hanoi(1)
cout

While loop seems to be passing variables inversely from the Boolean condition

I've tested so many scenarios and it works without the while loop; but I just cant seem to figure out whats messing it up. if I pick an int in the target range 1-3 it passes and then freezes and i have to ctrl c the program out.
And if I pick a number outside that range it lets it pass in to the while loop and call the function. I'm very confused and this is the first program I've written with classes; so I feel like that probably is the issue.
Thanks.
#include <iostream>
using namespace std;
class Elevator
{
public:
void floorControl();
// Outputs floor actions and lets a user pick a floor number
int status();
// outputs floor positon
private:
int floorPosition = 1;
};
int main()
{
Elevator building[3];
int elevatorSelect;
cout << "\tElevator Status\n\tA\tB\tC\n"
<< "\t" << building[0].status() << "\t" << building[1].status()
<< "\t" << building[2].status() << endl
<< "\tWhich elevator do you want (1=A, 2=B, 3=C, or other to exit) ? ";
cin >> elevatorSelect;
cout << "\t" << elevatorSelect << endl;
while((elevatorSelect <= 3) && (elevatorSelect >=1));
{
building[elevatorSelect-1].floorControl();
cout << "\tElevator Status\n\tA\tB\tC\n"
<< "\t" << building[0].status() << "\t" << building[1].status()
<< "\t" << building[2].status() << endl
<< "\tWhich elevator do you want (1=A, 2=B, 3=C, or other to exit) ? ";
cin >> elevatorSelect;
cout << "\t" << elevatorSelect << endl;
}
return 0;
}
void Elevator::floorControl()
{
int floorSelect;
if(floorPosition > 1)
{
cout << "\tStarting at floor " << floorPosition << endl;
for(int i=1; i>floorPosition; floorPosition--)
cout << "\t Going down - now at floor " << floorPosition-1 << endl;
cout << "\tStopping at floor " << floorPosition << endl;
}
cout << "\tWhich floor do you want? ";
cin >> floorSelect;
if ((floorSelect < 1 )|| (floorSelect > 10))
cout << "\t**You pick up some dust off the wall; you missed**\n";
else
{
cout << "\tStarting at floor " << floorPosition << endl;
for (floorSelect; floorSelect > floorPosition; floorPosition++)
cout << "\t Going up - now at floor " << floorPosition+1 << endl;
cout << "\tStopping at floor " << floorPosition << endl;
}
}
int Elevator::status()
{
return floorPosition;
}

voids not being read

I'm working on an Arena-ish console game. I want it so that I can have a void to make you fight certain monsters, instead of having to the monster fight out every time. Here's my code:
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;
char select;
int randnum;
int level=1;
int maxhp=10;
int hp=maxhp;
int mhp;
int exp;
int dmg;
int m_maxhp;
int req_exp=10;
int day;
char boot;
int a;
ifstream leveli;
ofstream levelo;
ifstream playerhpi;
ofstream playerhpo;
ifstream expi;
ofstream expo;
ifstream maxhpi;
ofstream maxhpo;
ifstream req_expi;
ofstream req_expo;
ifstream dayi;
ofstream dayo;
void wait( time_t delay )
{
time_t timer0, timer1;
time( &timer0 );
do {
time( &timer1 );
} while (( timer1 - timer0 ) < delay );
}
// This is the void that's not being called
void bat()
{
m_maxhp=10;
mhp=m_maxhp;
do{
dmg= rand() % 4 + 1;
cout << "Batt attacks you for " << dmg;
hp=hp-dmg;
cout << ", leaving you with [" << hp << "/" << maxhp << "]" << endl;
wait(1);
if(hp<=0)
{
cout << "You've lose. Try harder next time.";
exp=exp/2;
day=day+1;
dayo.open("daynumber.dat");
dayo << day;
dayo.close();
}
else if(mhp<=0)
{
cout << "You have killed the Bat. You gain 6 EXP." << endl;
exp=exp+6;
day=day+1;
dayo.open("daynumber.dat");
dayo << day;
dayo.close();
expo.open("experience.dat");
expo << exp;
expo.close();
}
}while(mhp>0);
}
int main()
{
leveli.open("level.dat");
leveli >> level;
leveli.close();
playerhpi.open("health.dat");
playerhpi >> hp;
playerhpi.close();
expi.open("experience.dat");
expi >> exp;
expi.close();
maxhpi.open("maxhealth.dat");
maxhpi >> maxhp;
maxhpi.close();
req_expi.open("req_exp.dat");
req_expi >> req_exp;
req_expi.close();
cout << "Data successfully loaded. Start the game now? y/n" << endl;
boot=_getch();
if(boot=='n')
{
cout << "Exiting..." << endl;
wait(3);
exit(0);
}
else if(boot=='y'){
do{
if (exp==req_exp)
{
level=level+1;
cout << "Level Up! You are now level " << level << "!" << endl;
exp=0;
req_exp=req_exp*1.5;
req_expo.open("req_exp.dat");
req_expo << req_exp;
req_expo.close();
levelo.open("level.dat");
levelo << level;
levelo.close();
}
else{
cout << endl << "Day " << day << " in The Arena." << endl << "1. Fight" << endl << "2. Stats" << endl << "3. Full Heal" << endl << "4. Half Heal" << endl;
select=_getch();
if(select=='1')
{
srand((unsigned)time(0));
randnum = rand() % 500 + 1;
// cout << "*DEBUG* " << randnum << endl;
// This part doesn't work
if(randnum<300 && level<4)
{
cout << "You've been chosen to fight a Bat!" << endl;
wait(1.5);
void bat();
}
else
{
}
}
else if(select=='2')
{
cout << endl << "Health: [" << hp << "/" << maxhp << "]" << endl << "Level: [" << level << "]" << endl << "Experience: " << "[" << exp << "/" << req_exp << "]" << endl;
wait(0.5);
}
else
{
cout << "Invalid Command";
}
}
}while (boot=='y');
}
return 0;
}
Am I using voids incorrectly? If so, could someone point out what I should change?
if(randnum<300 && level<4)
{
cout << "You've been chosen to fight a Bat!" << endl;
wait(1.5);
void bat(); // ?
}
What is expected behavior here? void bat(); is a function declaration. This just introduces the name bat and does nothing else. It doesn't call a function named bat. In case you need just to call bat, you should write:
bat(); // a call to "bat"
When you call the function, you omit the return type, e.g. your code:
// This part doesn't work
if(randnum<300 && level<4)
{
cout << "You've been chosen to fight a Bat!" << endl;
wait(1.5);
void bat();
...
Should read:
// This part doesn't work
if(randnum<300 && level<4)
{
cout << "You've been chosen to fight a Bat!" << endl;
wait(1.5);
bat();
...

C++ - program has stopped working

The code that I posted below is supposed to work in recursion (the Sort() function) even up to 1kk times. The problem is: when the Sort() function gets into loop number 43385 the console stops working and alerts: "The program has stopped working". Is it a problem with memory? If yes, where is the bad part of the code? Greetings.
#include <iostream>
#include <string>
using namespace std;
string a, b;
int n=0,i=0,counter=0;
int Sort(int i)
{
int x=0,y=0,tmp0=0;
char tmp1;
for(x=i;x<n;x++) {
if(a[x]==b[i]){
tmp0=x;
tmp1=a[x];
break;
}
else
continue;
}
for(y=tmp0;y>=i;y--)
y==i ? a[i]=tmp1 : a[y]=a[y-1];
counter+=tmp0-i;
if(i==n-1)
return counter;
else
Sort(i+1);
}
int main()
{
cin >> n >> a >> b;
Sort(0);
return 0;
}
Perhaps a call stack overflow because of too deep recursion?
To add to iltal's comment, you may want to print out information on strings a, b: a.size(), a.length(), a.capacity(), a.max_size()
I'm not sure what this code is trying to do. Here's a revision, with some print statements added, along with a random string generator.
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
string a, b;
int n=0,i=0,counter=0;
int Sort(int i)
{
int x=0,y=0,tmp0=0;
char tmp1;
for(x=i;x<n;x++) {
if(a[x]==b[i]){
tmp0=x;
tmp1=a[x];
cout << "x = " << x << " set tmp0 to " << tmp0 << " and tmp1 to " << tmp1 << endl;
break;
}
else
continue;
}
for(y=tmp0;y>=i;y--)
y==i ? a[i]=tmp1 : a[y]=a[y-1];
counter+=tmp0-i;
cout << " endof sort: a is " << a << endl;
cout << " b is " << b << endl;
if(i==n-1) {
cout << "Returning counter " << counter << endl;
return counter;
} else {
cout << "Running sort(" << i << " + 1)" << endl;
Sort(i+1);
}
}
string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
return result;
}
int main()
{
n = 50;
srand(time(NULL));
string a0, b0;
a0 = randomStrGen(n);
a = a0;
b0 = randomStrGen(n);
b = b0;
// cin >> n >> a >> b;
cout << "Max string size is " << a.max_size() << endl;
cout << "Calling sort" << endl
<< " n is " << n << endl
<< " a is " << a << endl
<< " b is " << b << endl;
Sort(0);
cout << " endof program: a inital: " << a0 << endl;
cout << " a final: " << a << endl;
cout << " b inital: " << b0 << endl;
cout << " b final: " << b << endl;
return 0;
}
counter is of type int but it has a lot of values summed in it which may be in all larger than int. maybe try int64?
You could hard code some test cases, like n = 20, a = "xyz...", b = "abc...", and add print statements to your sort function to track what is going on. Also, it may be helpful to add some comments to clarify what the purpose of the different loops are.

program crashes at CIN input | C++

so i made a DOS program however my game always crashes on my second time running to the cin function.
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
//call functions
int create_enemyHP (int a);
int create_enemyAtk (int a);
int find_Enemy(int a);
int create_enemyDef (int a);
// user information
int userHP = 100;
int userAtk = 10;
int userDef = 5;
string userName;
//enemy Information
int enemyHP;
int enemyAtk;
int enemyDef;
string enemies[] = {"Raider", "Bandit", "Mugger"};
int sizeOfEnemies = sizeof(enemies) / sizeof(int);
string currentEnemy;
int chooseEnemy;
// ACTIONS
int journey;
int test;
int main()
{
// main menu
cout << "welcome brave knight, what is your name? " ;
cin >> userName;
cout << "welcome " << userName << " to Darland" << endl;
//TRAVELING
MENU:
cout << "where would you like to travel? " << endl;
cout << endl << " 1.> Theives Pass " << endl;
cout << " 2.> Humble Town " << endl;
cout << " 3.> Mission HQ " << endl;
cin >> journey;
if (journey == 1)
{
// action variable;
string c_action;
cout << "beware your journey grows dangerous " << endl;
//begins battle
// Creating the enemy, HP ATK DEF AND TYPE. ;
srand(time(0));
enemyHP = create_enemyHP(userHP);
enemyAtk = create_enemyAtk(userAtk);
enemyDef = create_enemyDef(userDef);
chooseEnemy = find_Enemy(sizeOfEnemies);
currentEnemy = enemies[chooseEnemy];
cout << " Here comes a " << currentEnemy << endl;
cout << "stats: " << endl;
cout << "HP :" << enemyHP << endl;
cout << "Attack : " << enemyAtk << endl;
cout << "Defense : " << enemyDef << endl;
ACTIONS:
cout << "Attack <A> | Defend <D> | Items <I>";
cin >> c_action;
//if ATTACK/DEFEND/ITEMS choice
if (c_action == "A" || c_action == "a"){
enemyHP = enemyHP - userAtk;
cout << " you attack the enemy reducing his health to " << enemyHP << endl;
userHP = userHP - enemyAtk;
cout << "however he lashes back causing you to have " << userHP << "health left " << endl;
//end of ATTACK ACTION
}
the last line "cin >> c_action crashes. i use two other pages. they just create the functions. is it a complier issue. also why does my complier always shutdown after it runs he app. is there a way to stop it?
A few hints:
I never use forward declarations of functions ( such as "int create_enemyHP (int a);" ) if I can avoid them. If you do this then there are two places in your code that must be correct for your program to work. It makes life easier if there is always a "single source of truth"
Have you run this code through the debugger? It will help you find problems much more quickly.
If your c_action variable is only intended to be a char, I'd suggest to use a char variable, rather than a string.
You might want to try this way, and if you're still faced with an error, you might give
scanf("%c", &c_action); //assuming you used a char.
I didn't understand if the program crashes before you type the "action" or after. Because if it crashes before, then I think your problems are caused by white spaces characters in the input buffer.