Problem with using strings

Hello. I am currently writing code for a text based game and for some reason when I type in to display a certain variable (string MeleeWeapon) it just puts a space instead. Below is the code involved. I just started using strings and arrays so if there is a problem with any of them please tell me.

[code] int TotalHp = 15;
int RatHp[3] = { 5, 5, 6};
int MeleeWeaponDamage = 5;
string MeleeWeaponArray[2] = { "fists", "iron shortsword" };
int CombatHp = TotalHp;
string MeleeWeapon;

cout << "\nDo you take the iron shortsword as your new melee weapon? y/n: ";
char TakeNewWeapon = ' ';
cin >> TakeNewWeapon;

while((TakeNewWeapon != 'y') && (TakeNewWeapon != 'n'))
{
cout <<"Your input is invalid. Please type y for yes or n for no: ";
cin >> TakeNewWeapon;
}


if(TakeNewWeapon == 'y')
{
MeleeWeapon = MeleeWeaponArray[2];
MeleeWeaponDamage = 7;
cout << "Your new weapon is an iron shortsword that does 7 damage.";
}

else
{
cout <<"You leave the iron shortsword where it is.";
}

cout << "\n\n\n\n\n\nYOU HAVE BEGUN AN ENCOUNTER BETWEEN 3 RATS 2 WITH " << RatHp[1];
cout << “HP AND 1 WITH 6 HP\nYOU CURRENTLY HAVE " << CombatHp <<"HP.";
cout << "\n\nYour weapon is "<< MeleeWeapon << " and deals a maximum damage of " << MeleeWeaponDamage << " damage\n";
/code]
Last edited on
replace the && with || in the while loop
when i do this and input 'y' or 'n' it says input invalid. Also what does || mean
nevermind i found the error. Because arrays start with 0 it should be

MeleeWeapon = MeleeWeaponArray[1]
&& was correct. || is the logical or.


valid indices for MeleeWeaponArray are 0 to 1. 2 is not a valid index, so when you do:

MeleeWeapon = MeleeWeaponArray[2]; you are accessing memory that is out of bounds.
... i know what || is. once in the loop lets say you put in 'y'
the condition (expanded to the value of the variable instead of the variable itself) becomes
while(('y' != 'y' /*this would break it since its ==but...*/) && ('y' != 'n' /*y != n so its going yo loop again*/))
while(('y' != 'y' /*this would break it since its ==but...*/) && ('y' != 'n' /*y != n so its going yo loop again*/))
Do you actually understand the difference between AND and OR?
(false && x) == false
(false || x) == x

If x == 'y', then it's false that x is different from both 'y' and 'n', since it is equal to one of them.
yes i do. you know what fine. its not that important to me. but dont come posting back when you accidentally enter 'm' and find your self in an infinite loop
Topic archived. No new replies allowed.