# help with a code

## Recommended Posts

zeltrax5    100
Hey, I recently made text game but can't get this statement to work properly: void Attack() { cout<<"You have attacked with your sword"<<endl; cout<<"Your sword has been destroyed during the hit, your target had killed you"; || cout<<"Your have slain the enemy with your sword"; }; it's a simple function I located in a class... when the game gets to the point where the function has to run it ALWAYS prints "Your sword has been destroyed...", while I want it to randomly select one of these quotes. Can any1 help please?

##### Share on other sites
tiemykim    100
You can't use the OR operator like that '||'. I am surprised that compiles. Instead you can do something like this.

This will create a random number between 1 - 3, depending on what it is it will output one of your sentences.

#include <time.h>	void Attack() {	 srand ( time(NULL) );	int randomNum = rand() % 3 + 1; 	if(randomNum == 1){		cout<<"You have attacked with your sword"<<endl;	}else(randomNum == 2){		cout<<"Your sword has been destroyed during the hit, your target had killed you"; 	}else{		cout<<"Your have slain the enemy with your sword";	}};

##### Share on other sites
namar777    488
How i would go about it...

[source lang = "c++"]'void Attack() { int choice = rand() % 3; //include #include <stdlib.h> switch(choice){     case 0:          cout<<"You have attacked with your sword"<<endl;      break;     case 1:          cout<<"Your sword has been destroyed during the hit, your target had killed you";      break;     case 2:        cout<<"Your have slain the enemy with your sword";     break;}};

##### Share on other sites
Hyrcan    144
Considering that Attack() will most likely get called several times, it's not a good idea to call srand() in the function to seed the PRNG. Call it once at the start of the application.

You might also think about the probabilities associated with each event, i.e. if it makes much sense to think of every event to be equally probable.

##### Share on other sites
Small point, I think he wants it to always print the first line. So that should be before the if or switch statement.

##### Share on other sites
zeltrax5    100
thanks it workd properly now