Problem Outputting Array Element

This is a discussion on Problem Outputting Array Element within the C++ Programming forums, part of the General Programming Boards category; I am having problems trying to output a string thats in an array. There are three member function of a ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    17

    Problem Outputting Array Element

    I am having problems trying to output a string thats in an array. There are three member function of a class that I am trying to use to get this done.

    The first is setPlayerAbilities() which assigns what abilities a player can have.

    Code:
    void Player::setPlayerAbilities(){
    	if (PlayerState == "Mage"){
    		string MageAbilities[14]={"Mana Burn", "Fireball", "Frostbolt", "Lightening Bolt", "Chain Lightening", "Earth Shatter",
    								  "Mana Shield", "Mana Siphon", "FlameWalker", "WaterWalker", "Mana Shield Nova", "Mana Siphon Nova", 
    								  "FlameWalker Nova", "WaterWalker Nova" };
    		
    		}
    
    	if (PlayerState == "Warrior"){
    		string WarrAbilities[11]={"Howl", "Sunder", "FireBlade", "IceBlade", "LighteningBlade", "Soul Siphon", "Berserk",
    								  "Sweeping Strikes", "Hostile Charge", "Heal", "Attack" };
    		
    		}
    
    }
    The second is a function that controls the menu options. It starts by giving the player 2 choices (1.CastSpell or 2. VeiwSpells). The loop I have it in is horrendous I know but it works for now. Once the player selects 1 (CastSpell), I then pass the integer cast to the member function CastSpell() (which in turn calls the function). There is a lot of text here...Ill try to cut it down as much as I can so you see more of the code, less of the text.
    Code:
    void Player::callPlayerUI(){
    	int choice = 0;
    	int cast;
    	int use;
    	int control; // This is used to prevent the error message after inputing a invalid choice options when viewing spells
    
    	if (PlayerState == "Mage"){
    		setPlayerAbilities();
    		while (choice >= 3 || choice < 1){
    
    		cout <<"=============================================="<<endl;
    		cout <<"Hit Points: test value       Mana: test value|"<<endl;
    		cout <<"| 1.CastSpell                    2.ViewSpells|"<<endl;
    		cout <<"=============================================="<<endl;
    		cin >>choice;
    
    		if (choice == 1){
    			cout <<"============================================="<<endl;
    			cout <<"|[1]ManaBurn          [8]Mana Siphon        |"<<endl;
    			cout <<"|[2]Fireball          [9]FlameWalker        |"<<endl;
    			cout <<"|[3]Frostbolt         [10]WaterWalker       |"<<endl;
    			cout <<"|[4]LBolt             [11]Mana Shield Nova  |"<<endl;
    			cout <<"|[5]ChainL            [12]Mana Siphon Nova  |"<<endl;
    			cout <<"|[6]Earth shatter     [13]FlameWalker Nova  |"<<endl;
    			cout <<"|[7]Mana Shield       [14]WaterWalker Nova  |"<<endl;
    			cout <<"============================================="<<endl;
    			cin >>cast;
    			CastSpell(cast);
    
    		}
    		if (choice == 2){
    			cout <<"+++++++++++++++++LIST SPELLS+++++++++++++++++++++++++++++"<<endl;
    			cout <<"+++++++++++++++++++++++++++END SPELLS+++++++++++++++++++++++++"<<endl;
    			choice = 0;
    			control = 1;
    		}
    		if (choice > 2 || choice <1 && control != 1){
    			cout <<"Error, try again"<<endl;
    		choice = 0;
    		}
    		}
    		}
    		
    		/* YOU CAN IGNORE EVERYTHING FROM HERE DOWN */
    		/* =+!+!+!+!+!+!+!+ Start Warrior Section +!+!+!+!+!+!+!+ */
    
    	if (PlayerState == "Warrior") {
    		while (choice >= 3 || choice < 1){
    		cout <<"=============================================="<<endl;
    		cout <<"|              Hit Points: test value        |"<<endl;
    		cout <<"| 1.UseAbility                2.ViewAbilities|"<<endl;
    		cout <<"=============================================="<<endl;
    		cin >>choice;
    
    		if (choice == 1){
    			cout <<"============================================="<<endl;
    			cout <<"|[1]Attack            [7]Soul Siphon        |"<<endl;
    			cout <<"|[2]Sunder            [8]Berserk            |"<<endl;
    			cout <<"|[3]Fire Blade        [9]Sweeping Strikes   |"<<endl;
    			cout <<"|[4]Ice Blade         [10]Hostile Charge    |"<<endl;
    			cout <<"|[5]Lightening Blade  [11]Heal              |"<<endl;
    			cout <<"|[6]Howl                                    |"<<endl;
    			cout <<"============================================="<<endl;
    			cin >>use;
    		}
    		if (choice == 2) {
    			cout <<"\n\n!+!+!+!+!+!+!+!+!+!+!+!+Abilities+!+!+!+!+!+!+!+!+!+!+!+!+"<<endl;
    			choice = 0;
    			control = 1;
    		}
    			if (choice > 2 || choice <1 && control != 1){
    			cout <<"Error, try again"<<endl;
    			choice = 0;
    		}
    
    	}
    	if (PlayerState != "Warrior" && PlayerState != "Mage"){
    		cout <<"Error, no PlayerState!!!!"<<endl;
    	}
    	}
    }
    The last is the CastSpell() member function that is supposed to receive the integer (cast) from the previous function and output an element of the array (cast - 1 since array elements start from 0).

    Code:
    void Player::CastSpell(int cast){
    	setPlayerAbilities();
    	cout <<MageAbilities[cast-1];
    }
    However, nothing is printed or output. I've changed the cout message to say "You have casted " <<MageAbilities[cast-1] <<", grats"...but it prints everything but the array element.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,738
    One problem I see is that the arrays created in Player::setPlayerAbilities() are local variables. As such, they do not exist in Player::CastSpell(int).

    By the way, are you sure you do not want to learn about inheritance and polymorphism first? Your project looks like an excellent chance to experiment with these object oriented concepts.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,650
    The MageAbilities array is created local to the setPlayerAbilities method; accessing this outside of the method results in undefined behavior.

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    17
    Quote Originally Posted by laserlight View Post
    One problem I see is that the arrays created in Player::setPlayerAbilities() are local variables. As such, they do not exist in Player::CastSpell(int).

    By the way, are you sure you do not want to learn about inheritance and polymorphism first? Your project looks like an excellent chance to experiment with these object oriented concepts.
    I was starting to think that. I tried modifying setPlayerAbilities to return the array but failed miserably and it really doesn't seem like a great idea.

    Would doing away with setMageAbilities() member function and just defining them as private variables be the best way to do it?

    As far as using polymorphism and inheritance, I prefer to get the entire project done first without learning anything new. After its complete I plan on reviewing the code, cleaning it up and then start looking at learning and applying those tools.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,738
    I tried modifying setPlayerAbilities to return the array but failed miserably and it really doesn't seem like a great idea.
    It looks like all mages will have those same abilities, as will all warriors. As such, you could make them into static const member arrays of strings.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Apr 2008
    Posts
    17
    Quote Originally Posted by laserlight View Post
    It looks like all mages will have those same abilities, as will all warriors. As such, you could make them into static const member arrays of strings.
    I am not sure what you mean as I don't know what it does.

    I changed my code a bit. I removed setPlayerAbilties and just declared the array as a private variable but gives me errors about undeclared identifiers and syntax errors.

    Here is the class
    Code:
    class Player {
    public:
    	void setPName(string); 
    	string getPName();
    	string getPlayerState(int); //set up at StartGame()...int is either 1 for warrior or 2 for mage
    	//void setPlayerAbilities();  temporarily removed
    	void setPlayerStats(); // health,mana,stamina,intel,ap,sp,agility,defense,luck,str
    	string CastAbility(); // casts ability
    	string getPlayerLoc(); // gets the players location;
    	void PInventory(); // may not be used if I can help it
    	void callPlayerUI(); // used to bring up options for doing all things
    	int modifyStats(); // lower currentHealth and/or mana based on damage taken or spells casted
    	void CastSpell(int); // Recieves cast int from callUI function
    	friend class Game;
    private:
    	string setPlayerLoc; // sets player location
    	int PMaxMana; // players max mana
    	int PMaxHealth; // players max health
    	int PStamina; // players stamina
    	int PAgility; // players chance to dodge
    	int PAP; // players attack power
    	int PIntel; // players intellect
    	int PSP; // players spell power (+damage)
    	int PStr; //players strength
    	int PLuck; // players luck
    	int currentHP; //current health
    	int currentMP; // current mana
    	string PlayerState; // hold the sting of what class the player is...warrior or mage
    	string PName; // players name
    	string MageAbilities[14]={"Mana Burn", "Fireball", "Frostbolt", "Lightening Bolt", "Chain Lightening", "Earth Shatter",
    							  "Mana Shield", "Mana Siphon", "FlameWalker", "WaterWalker", "Mana Shield Nova", "Mana Siphon Nova", 
    							  "FlameWalker Nova", "WaterWalker Nova"}; // array of which abilites the Mage can use
    	string WarrAbilities[1]; // array of which abilities the warrior can use
    	string castedSkill;
    };
    And the member where I try to use it.
    Code:
    void Player::CastSpell(int cast){
    	// setPlayerAbilities(); removed for now
    	cout <<MageAbilities[cast];
    }
    I get the following errors that point me to where I declare the array and one in the cout statment of the member function.
    Code:
    1>c:\documents and settings\xxxx\my documents\visual studio 2008\projects\simple rpg\simple rpg\Player.h(33) : error C2059: syntax error : '{'
    
    1>c:\documents and settings\xxxx\my documents\visual studio 2008\projects\simple rpg\simple rpg\Player.h(33) : error C2334: unexpected token(s) preceding '{'; skipping apparent function body
    
    1>c:\documents and settings\xxxx\my documents\visual studio 2008\projects\simple rpg\simple rpg\Player.h(325) : error C2065: 'MageAbilities' : undeclared identifier

  7. #7
    The larch
    Join Date
    May 2006
    Posts
    3,573
    You cannot initialize members within class declarations (except static integral constants).

    The correct way is to make MageAbilities static:
    Code:
    class Player
    {
        ... elided ...
        static string MageAbilities[14]; //magic numbers are not good
    };
    And then declare and initialize it outside the class declaration:
    Code:
    string Player::MageAbilities[14] = {"Mana Burn", etc};
    Making it static is under the assumption that all Players are going to have the same list of MageAbilities. Of course you could for example have a regular vector<string> and add abilities to it as any individual player learns them.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with copying a string into array in a struct
    By JFonseka in forum C Programming
    Replies: 15
    Last Post: 05-04-2008, 05:07 AM
  2. simple array of char array problem
    By cloudy in forum C++ Programming
    Replies: 5
    Last Post: 09-10-2006, 12:04 PM
  3. 2d array question
    By gmanUK in forum C Programming
    Replies: 2
    Last Post: 04-21-2006, 12:20 PM
  4. Deleting element from an array problem
    By xamlit in forum C Programming
    Replies: 5
    Last Post: 12-03-2005, 03:53 PM
  5. problem: reading user input into an array
    By alpha561 in forum C Programming
    Replies: 13
    Last Post: 05-24-2002, 07:23 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21