C ++ program ends too soon

I am very new to C ++ and I wrote this piece of code. Which is called to go in that order. 1. asks for a name, then greets the person 2. asks for his weapon of choice 3. chooses a random number and does damage panda

I had all three of these steps. Then I decided, maybe I could change the range of my random number using the variables in my rand () function bracket. This did not work as planned, so I tried to go back. Thanks in advance for any help received. I would have no idea how I can find this over the Internet, so I came here. Hoping someone could identify my problem. I am using the NetBeans IDE.

My problem: he first asks for my name, then I enter my name and it greets me. But then he finishes the code. Before you try to execute the rest of the code. My thoughts are that I obviously missed something that I had to return.

Welcome to panda hunter! Please enter your name: Darryl Welcome!, Darryl! RUN SUCCESSFUL (total time: 3s) 

But I looked through it many times and could not find anything bad. Also my thoughts are that something is wrong with this line, because it fails to continue:

  cout << "Pick your weapon of choice! Then press enter to attack: "; 

. Here is the contents of the whole file:

 #include <iostream> #include <cstdlib> #include <stdio.h> /* printf, scanf, puts, NULL */ #include <stdlib.h> /* srand, rand */ #include <time.h> using namespace std; string getName(){ string name; cin >> name; return name; } string weaponChoice(){ string weapon; cin >> weapon; return weapon; } int rand(){ int damagePanda = rand() % 20 + 1; return damagePanda; } int main() { srand(time(0)); int pandaHealth = 100; int userHealth = 100; cout << ("Welcome to panda hunter! Please enter your name: "); cout << "Welcome!, " << getName() << "!" << endl; cout << "Pick your weapon of choice! Then press enter to attack: "; cout << "You surprise the panda with your " << weaponChoice() << ", dealing " << rand() << " damage!"; pandaHealth = pandaHealth - rand(); cout << "Panda has " << pandaHealth << " health remaining"; char f; cin >> f; return 0; } 
+4
source share
1 answer
 int rand(){ int damagePanda = rand() % 20 + 1; return damagePanda; } 

Recursive call. You probably blew your stack here.

The compiler should have warned you here! Not sure why this is not so.

Change to

 int myrand(){ int damagePanda = rand() % 20 + 1; return damagePanda; } 

Also change

 cout << "You surprise the panda with your " << weaponChoice() << ", dealing " << rand() << " damage!"; 

to

 cout << "You surprise the panda with your " << weaponChoice() << ", dealing " << myrand() << " damage!"; 

It is also probably necessary to change

 pandaHealth = pandaHealth - rand(); 

The last change probably depends on your application logic - I have not tried to figure it out.

+10
source

Source: https://habr.com/ru/post/1481199/


All Articles