How to display std::string value in std::cout

*hi guys. I’m writing a story adventure on C++ for my course on Codecademy. Can you have a look at the code below. *

I want the code to be able to read the value of the string weapon. Basically it will change depending on user choice. when I run this code I get a blank where I want it to cout my weapon value. EG. If user picks 1 in cint, I want the value of the string “weapon” to be “broadsword” and then to recall it in a cout eg. "your weapon of choice is " [weapon value entered]. Not sure if I’m making sense? TIA for your help! Gareth

#include <stdlib.h>

int main()
std::cout << “please choose your weapon 1) Sword, or 2) Arrows\n\n”;;

int answer = 0;
int weapon_strength = 0;
int distance = 0;
std::string weapon, broadsword, bow_and_arrow;

std::cin >> answer; “\n\n\n”;

while (answer !=1 && answer !=2) {std::cout <<
" please select 1 or 2\n\n\n\n\n\n"; std::cin >> answer;}

if (answer ==1)
{weapon = broadsword; weapon_strength = weapon_strength +10; distance = distance +2; std::cout <<
" You’ve picked the "; std::cout << weapon; std::cout << “! A great choice - it has endurance but short range…\n\n\n”;}

else if (answer ==2) {weapon = bow_and_arrow; distance =10; weapon_strength = weapon_strength + 5; std::cout <<
" Ah yes, the " << weapon << “! A nice choice at distance, but wont do quite as much damage.\n\n\n”;}

I think you left out setting the values of the broadsword and bow_and_arrow string variables somewhere:

broadsword = "broadsword";
bow_and_arrow = "bow and arrow";


I guess you could use a switch statement, or some if and else-if stuff.

switch (answer) {
  case 1: 
    weapon = "broadsword"; break;
  case 2: 
    weapon = "bow and arrow"; break;
    weapon = "fist"; break;
std::cout << "Your weapon of choice was the " << weapon << ".\n";

Or you could use an array to do that.

std::string weaponChoices[] = {"broadsword", "bow and arrow"};
weapon = weaponChoices[answer - 1];
std::cout << "Your weapon of choice was the " << weapon << ".\n";
1 Like