String Game, creating a specific Loop? c++ - c++

Im new to programming and C++ and I started making a little string type game for fun, which gives the user two options through out the program, but in the final part of the program i cant get it to output a unique option for the final input(makeCure) - which i only want to output at the end not through out the program. Hope Im making sense :/ .Iv tried and tried and tried and the more i try the more probloms I create. Iv shown below in my code where Im sure the problom lies. Any advice would much appreciated.
#include<iostream>
#include<string>
using std::string;
bool intro(void);
void room(bool enemy, bool data, bool cure, string description);
//player stats
string Name = "";
//enemy states
string enemyName = "";
//data stats
string dataName = "";
//Cure - Option in room7 only
string makeCure = "";
//room descriptions(string constructs)
const string room1 = "You enter the first town of infected Zombies.";
const string room2 = "You are overwelmed by Zombies, and plunder into the sewers to escape.";
const string room3 = "You make your way to safety and find yourself in the Central Town Hall.";
const string room4 = "You decide to venture into the local forest to find the finalingrediants";
const string room5 = "You venture further for the final ingrediant, into a nearby Cave.";
const string room6 = "Its time for you to face the Zombie General!!!";
const string room7 = "You work day and Night in the Labs to make the Cure.";
int main(void)
{
if(intro())
return 0;
dataName = "First Ingrediant- Zombie Rags with infected DNA";
enemyName = "Zombie Soldior";
room(true, true, false, room1);
enemyName = "Massive Zombie Rat";
room(true, false, false, room2);
dataName = "Seconed Ingrediant- StemCells";
enemyName = "Mutated Scientists";
room(true, true, false, room3);
dataName = "Third Magic-Mushrooms";
room(false, true, false, room4);
dataName = "Fourth Final Ingrediant - Coffee Beans";
enemyName = "Commander Zombie";
room(true, true, false, room5);
enemyName = "Zombie General";
room(false, true, false, room6);
return 0;
makeCure = "Elixier to Save the World";
room(false, false, true, room7);
return 0;
}
bool intro(void)
{
using std::cout;
using std::cin;
cout << "Brave Soul!!! What is your name?\n";
cin >> Name;
cout << "Ahh... " << Name << " You say.." << "How about Zombie Slayer?.. Good, glad we agree!\n";
cout << "Humanity is in need of your Help, "
<< "The world is being infected by the\n"
<< "ZD1678 ZOMBIE VIRUS \n"
<< "And we need to send you to Cape Town to stop the central spread.\n"
<< "Your task will be tough, but we know you can do it \n"
<< "Will you accept the challenge?\n\n";
cout << "1)Yes. \n"
<< "2)No. \n\n";
int response;
cin >> response;
return !(response ==1);
}
void room(bool enemy, bool data, bool cure, string description)
{
using std::cout;
using std:: cin;
while(true)
{
cout << description.c_str() << "\n\n";
int response = 0;
do
{
cout << "Shall Our Hero continue his Quest?\n";
if(enemy)
cout << "1) Attack the "
<< enemyName.c_str() << "\n";
else if(!enemy)
cout << "1) venture further....";
if(data)
cout << "2)Pick up the "
<< dataName.c_str() << "\n";
cin >> response;
/* Trying to create the last if that only kicks in at room7( string makeCure )
* that displays the option to make the cure
* This is where my Problem is.
* Iv tried anouther if
* and else
* and while and nothing works, its just messes up everything..
* badly
*/
} while(response < 1 || response > 2);
switch(response)
{
case 1:
if(enemy)
{
enemy = !enemy;
cout << "You slay the deadly "
<< enemyName.c_str() << "\n";
}
else if(!enemy)
return;
break;
case 2:
data = !data;
cout << "You pick up the "
<< dataName.c_str() << "\n";
break;
}
}
}

what you probably want to do is dynamically generate a list of possible events each time you write out the list and present it to the user, then you can match the response to the list to get what the user wants to do. like this:
enum EventType
{
ET_Enemy,
ET_Item,
ET_Cure,
ET_Continue,
ET_MAX
};
void room(bool enemy, bool data, bool cure, string description)
{
using std::cout;
using std:: cin;
int currentEventChoices[ET_MAX];
int numEventChoices;
while(true)
{
cout << description.c_str() << "\n\n";
int response = 0;
do
{
numEventChoices = 0;
cout << "Shall Our Hero continue his Quest?\n";
if(enemy)
{
cout << (numEventChoices+1) << ") Attack the "
<< enemyName.c_str() << "\n";
currentEventChoices[numEventChoices] = ET_Enemy;
numEventChoices++;
}
if(data)
{
cout << (numEventChoices+1) << ") Pick up the "
<< dataName.c_str() << "\n";
currentEventChoices[numEventChoices] = ET_Item;
numEventChoices++;
}
if(cure)
{
cout << (numEventChoices+1) << ") cure related string "
<< makeCure.c_str() << "\n";
currentEventChoices[numEventChoices] = ET_Cure;
numEventChoices++;
}
cout << (numEventChoices+1) << ") venture further....\n"; // note if this is only meant to be an option if there is no enemy, put it in an else after the if(enemy)
numEventChoices++;
cin >> response;
} while(response < 1 || response > numEventChoices);
switch(currentEventChoices[response-1])
{
case ET_Enemy:
enemy = !enemy;
cout << "You slay the deadly "
<< enemyName.c_str() << "\n";
break;
case ET_Item:
data = !data;
cout << "You pick up the "
<< dataName.c_str() << "\n";
break;
case ET_Cure:
//do cure stuff
break;
case ET_Continue:
return;
}
}
}
the trouble you are having is that by just using a very static next of if/else statements each time you want to match the option number to the event, it gets very complex and messy, it was fine when there was just the 4 cases of there being an enemy or not, or data or not. but now you are adding another branch with cure, its just got really complex to do it that way.

It's a bit hard to understand what you need, so tell me if it's not what you wanted.
Using braces and indenting consistently can really help with this:
do {
cout << "Shall Our Hero continue his Quest?\n";
if (enemy) {
cout << "1) Attack the " << enemyName << "\n";
} else {
cout << "1) venture further....";
}
if (data) {
cout << "2) Pick up the " << dataName << "\n";
}
if (cure) {
cout << "2) take the " << makeCure << "\n";
}
cin >> response;
} while (response < 1 || response > 2);
and fix "case 2" in the switch part:
case 2:
if (data) {
data = false;
cout << "You pick up the " << dataName << "\n";
} else if (cure) {
// fill in ...
}
break;
Notes:
You can use endl (from std) instead of '\n'. cout << "hello" << endl;
You can pass many of your global variables as arguments, so you won't need them to be global (global is bad, in general).
Much of your game can be be squeeszed into arrays and structs - being "data driven" and "table driven". I don't know if you got there already, but you can try and identify these parts.
if(enemy) ... else if(!enemy) you don't need the !enemy part. it is implied by the else.

Related

Way to reduce else if statements when using string as condition

I'm making a terminal-like program (to calculate currency) with custom commands as input but I have a problem.
Every time I implement a new command, I have to add a new else if statement. This wouldn't be a problem but for a terminal-like program there can be a lot of commands.
Here is my code:
#include <iostream>
#include <string>
#include <Windows.h>
#include <math.h>
float user_balance = 0.0f;
float eur_in_czk = 24.0f; //ammount of czk in single euro
std::string currency = "czk";
bool czk_to_eur_enabled = true;
bool eur_to_czk_enabled = false;
//------------------START method definition---------------------------------------------------------
void czk_to_eur()
{
if (czk_to_eur_enabled) //to prevent using twice in a row
{
user_balance /= eur_in_czk;
user_balance = floorf(user_balance * 100) / 100; //limit to two decimal numbers
currency = "eur";
czk_to_eur_enabled = false;
eur_to_czk_enabled = true;
}
else
{
std::cout << "Your savings are already converted to " << currency << "!" << std::endl;
}
}
void eur_to_czk()
{
if (eur_to_czk_enabled) //to prevent using twice in a row
{
user_balance *= eur_in_czk;
user_balance = floorf(user_balance * 100) / 100; //limit to two decimal numbers
currency = "czk";
eur_to_czk_enabled = false;
czk_to_eur_enabled = true;
}
else
{
std::cout << "Your savings are already converted to " << currency << "!" << std::endl;
}
}
void set_balance(float new_balance)
{
user_balance = new_balance;
}
void add_balance(float new_balance)
{
user_balance += new_balance;
}
//------------------END method definition-----------------------------------------------------------
int main()
{
bool main_loop = true; //main loop enabler
float input_money;
std::string user_command = "";
std::cout << "This is currency converter v1.0 (czk to eur and back)\n\n\n" << std::endl;
while (main_loop) //main loop for currency converter
{
std::cout << "Input: ";
std::cin >> user_command;
std::cout << std::endl;
if ((user_command == "setbal") || (user_command == "SETBAL"))
{
std::cout << "Your balance is " << user_balance << " " << currency << ".\n";
std::cout << "Please enter desired value (" << currency << "): ";
std::cin >> input_money;
set_balance(input_money);
std::cout << "\n" << std::endl;
}
else if ((user_command == "addbal") || (user_command == "ADDBAL"))
{
std::cout << "Your balance is " << user_balance << " " << currency << ".\n";
std::cout << "Please enter desired value (" << currency << "): ";
std::cin >> input_money;
add_balance(input_money);
std::cout << "\n" << std::endl;
}
else if ((user_command == "balance") || (user_command == "BALANCE"))
{
std::cout << "Your balance is " << user_balance << " " << currency << "." << std::endl;
}
else if ((user_command == "curstat") || (user_command == "CURSTAT"))
{
std::cout << "Currency status is " << eur_in_czk << " czk in 1 eur." << std::endl;
}
else if ((user_command == "toeur") || (user_command == "TOEUR"))
{
czk_to_eur();
}
else if ((user_command == "toczk") || (user_command == "TOCZK"))
{
eur_to_czk();
}
else if ((user_command == "cheuv") || (user_command == "CHEUV"))
{
std::cout << "Change eur value (" << eur_in_czk << "): ";
std::cin >> eur_in_czk;
std::cout << std::endl;
}
else if ((user_command == "help") || (user_command == "HELP"))
{
std::cout << "SETBAL Sets balance.\n"
<< "ADDBAL Adds balance.\n"
<< "BALANCE Shows current balance.\n"
<< "CURSTAT Shows currency status.\n"
<< "TOEUR Converts czk to eur.\n"
<< "TOCZK Converts eur to czk.\n"
<< "CHEUV Changes eur currency value.\n"
<< "CLS Cleans terminal history.\n"
<< "EXIT Exits program.\n" << std::endl;
}
else if ((user_command == "cls") || (user_command == "CLS"))
{
system("CLS"); //funtion from Windows.h library
}
else if ((user_command == "exit") || (user_command == "EXIT"))
{
main_loop = false;
}
else
{
std::cout << "'" << user_command << "'"
<< "is not recognized as an internal or external command!\n";
std::cout << "Type 'HELP' to see available commands.\n" << std::endl;
}
}
return 0;
}
The bottom part of the code in while cycle is where the problem is.
Everything works fine but I would like to know, if there is any other way. And switch to my knowledge does not support string values as condition/dependency. (also I'm currently not using any custom classes and/or custom header files because this is just experiment.)
Is there any other way to do it?
Normally I would suggest using a std::map with a string as the key and a function as the value so that you could search the map for a command and then invoke the function associated with it. However, since that's already been mentioned in the comments I figured I'd get all fancy and provide a totally wack solution you probably shouldn't use.
This wack solution allows you to use string literals in a switch/case statement. This is possible by taking advantage of a feature of modern C++ called user defined literals that allow you to produce objects of user-defined type by defining a user-defined suffix much in the same way you append U to a integer literal to specify an unsigned value.
The first thing we'll do is define a user defined literal that produces a hash value that is calculated at compile time. Since this generates a hash value from the string it is possible to encounter collisions but that's dependant on the quality of the hash algorithm used. For our example we're going to use something simple. This following snippet defines a string literal with the suffix _C that generates our hash.
constexpr uint32_t djb2Hash(const char* str, int index = 0)
{
return !str[index]
? 0x1505
: (djb2Hash(str, index + 1) * 0x21) ^ str[index];
}
// Create a literal type for short-hand case strings
constexpr uint32_t operator"" _C(const char str[], size_t /*size*/)
{
return djb2Hash(str);
}
Now every time the compiler sees a string literal in the format of "Hello World"_C it will produce a hash value and use that in place of the string.
Now we'll apply this to your existing code. First we'll separate the code that takes the user command from cin and make the given command all lower case.
std::string get_command()
{
std::cout << "Input: ";
std::string user_command;
std::cin >> user_command;
std::cout << std::endl;
std::transform(
user_command.begin(),
user_command.end(),
user_command.begin(),
[](char ch) { return static_cast<char>(std::tolower(ch)); });
return user_command;
}
There now that we can get an all lowercase command from the user we need to process that so we'll take your original set of if/else statements and turn them into a simple switch/case statement instead. Now since we can't actually use string literals in the switch/case statement we'll have to fudge a little bit and generate the hash value of the users command for the switch part of the code. We'll also take all of your commands and add the _C suffix to them so that the compiler automatically generates our hash values for us.
int main()
{
bool main_loop = true; //main loop enabler
std::cout << "This is currency converter v1.0 (czk to eur and back)\n\n\n" << std::endl;
while (main_loop) //main loop for currency converter
{
const auto user_command(get_command());
switch(djb2Hash(user_command.c_str()))
{
case "setbal"_C:
std::cout << "Set balance command\n";
break;
case "addbal"_C:
std::cout << "Add balance command\n";
break;
case "balance"_C:
std::cout << "Get balance command\n";
break;
case "curstat"_C:
std::cout << "Get current status command\n";
break;
case "help"_C:
std::cout << "Get help command\n";
break;
case "exit"_C:
main_loop = false;
break;
default:
std::cout
<< "'" << user_command << "'"
<< "is not recognized as an internal or external command!\n"
<< "Type 'HELP' to see available commands.\n" << std::endl;
}
}
}
And there you have it. A totally wack solution! Now keep in mind that we're not really using strings in the switch/case statement, we're just hiding most of the details of generating hash values which are then used.

In printme function it sets all falses to true

I am creating a simple car creator game to practice things like inheritance and classes. And I am stumped by this. when I debug it says that the values are what they should be but then it goes to the printme function and it sets them to true no matter what.
cout << "Does your car have stripes?" << endl;
bool validInput8; // stops from sending code all of the place and mixing cars
string inputStripes;
inputStripes = lower(inputStripes);
do
{
cin >> inputStripes;
inputStripes = lower(inputStripes);
if (inputStripes == "yes")
{
sportscar.Stripes = true;
validInput8 = true;
}
else if (inputStripes == "no")
{
sportscar.Stripes = false;
validInput8 = true;
}
else
{
cout << "Your input is not valid. Please enter yes or no!" << endl;
cin.get();
validInput8 = false;
}
} while (!validInput8);
Continue();
cin.get();
clear();
sportscar.PrintCarDetails();
and this is the Print Function
#include "SportsCar.h"
SportsCar::SportsCar()
{
Spoilers = false;
Stripes = false;
}
void SportsCar::PrintCarDetails()
{
cout << "You have finished your car! You are " <<
ColorTypeToString(Color) << " and have " << numdoors << " doors!" << endl;
if (Spoilers = true)
{
cout << "Your sports car has some super sweet spoilers and you look like a total baller" << endl;
}
else if (Spoilers = false)
{
cout << "Your car doesnt have spoilers so you are boring" << endl;
}
if (Stripes = true)
{
cout << "Your car has stripes and you will often be confused as a racecar" << endl;
}
else if (Stripes = false)
{
cout << "You dont have stripes but your driving a sports car who can complain" << endl;
}
}`
You are using one = on your IF statements and not two. With one you are just assigning the value and not checking if it is actually true.

C++ Console Application, Outputting Incorrect Data

I've been working on a simple console application and was stopped when, upon compiling my latest code, it began outputting strings of text and integers which did not match what I have entered.
The purpose of the program thus far is simple: to input a string of data and for it to output correctly multiple times in the console application. Below I have linked the pseudocode.
Thanks in advance.
#include <iostream>
#include <string>
void printIntro();
void RunApp();
bool RequestRestart();
std::string GetAttempt();
int main() // entry point of the application
{
printIntro();
RunApp();
RequestRestart();
return 0;
}
void printIntro() {
// introduce the program
constexpr int WORD_LENGTH = 8; // constant expression
std::cout << "Welcome to the Bull and Cow guessing game\n";
std::cout << "Can you guess the " << WORD_LENGTH;
std::cout << " letter isogram I am thinking of?\n\n";
return;
}
void RunApp()
{
// loop for number of attempts
constexpr int ATTEMPTS = 5;
for (int count = 1; count <= ATTEMPTS; count++)
{
std::string Attempt = GetAttempt();
std::cout << "You have entered " << GetAttempt << "\n";
std::cout << std::endl;
}
}
std::string GetAttempt()
{
// receive input by player
std::cout << "Enter your guess: \n";
std::string InputAttempt = "";
std::getline(std::cin, InputAttempt);
return InputAttempt;
}
bool RequestRestart()
{
std::cout << "Would you like to play again?\n";
std::string Response = "";
std::getline(std::cin, Response);
std::cout << "Is it y?: \n" << (Response[0] == 'y'); //response must be in brackets
return false;
}
You have to change this line
std::cout << "You have entered " << GetAttempt << "\n";
instd::cout << "You have entered " << Attempt << "\n";
In this way you do not print the address of the function, just like you did before, but the variable in which you stored the return value of the GetAttempt function.
You are printing a pointer to GetAttempt. Instead print Attempt:-
std::cout << "You have entered " << Attempt << "\n";

C++ Why is my loop breaking?

I'm following a tutorial for making a MUD (text-based RPG), and I am having issues with my main function. If you'll look at the code, you'll see that when the player moves it will check for a random encounter, and if monster != 0, it will go into the combat loop. When I execute this in the command prompt, it will allow me to attack the monster, but it never makes it to the monster->attack(mainPlayer) function. It just goes back to the screen that states whether I want to move, rest, view stats, or quit. Any help with this would be greatly appreciated!
#include "stdafx.h"
#include "Map.h"
#include "Player.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
srand( time(0) );
Map gameMap;
Player mainPlayer;
mainPlayer.createClass();
// Begin adventure
bool done = false;
while( !done )
{
// Each loop cycle we output the player position and
// a selection menu.
gameMap.printPlayerPos();
int selection = 1;
cout << "1) Move 2) Rest 3) View Stats 4) Quit: ";
cin >> selection;
Monster* monster = 0;
switch( selection )
{
case 1:
// Move the player
gameMap.movePlayer();
// Check for a random encounter. This function
// returns a null pointer if no monsters are
// encountered.
monster = gameMap.checkRandomEncounter();
// 'monster' not null, run combat simulation.
if( monster != 0)
{
// Loop until 'break' statement.
while( true )
{
// Display hitpoints
mainPlayer.displayHitPoints();
monster->displayHitPoints();
cout << endl;
// Player's turn to attack first.
bool runAway = mainPlayer.attack(*monster);
if( runAway )
{
break;
}
if( monster->isDead() )
{
mainPlayer.victory(monster->getXPReward());
mainPlayer.levelUp();
break;
}
monster->attack(mainPlayer);
if( mainPlayer.isDead() )
{
mainPlayer.gameover();
done = true;
break;
}
}
// The pointer to a monster returned from
// checkRandomEncounter was allocated with
// 'new', so we must delete it to avoid
// memeory leaks.
delete monster;
monster = 0;
}
break;
case 2:
mainPlayer.rest();
break;
case 3:
mainPlayer.viewStats();
break;
case 4:
done = true;
break;
} // End switch statement
} // End While statement
} // End main function
Here is the Player::attack function:
bool Player::attack(Monster& monster)
{
int selection = 1;
std::cout << "1) Attack 2) Run: ";
std::cin >> selection;
std::cout << std::endl;
switch( selection )
{
case 1:
std::cout << "You attack the " << monster.getName()
<< " with a " << mWeapon.mName << std::endl;
if( Random(0, 20) < mAccuracy )
{
int damage = Random(mWeapon.mDamageRange);
int totalDamage = damage - monster.getArmor();
if( totalDamage <= 0)
{
std::cout << "Your attack failed to penetrate the "
<< monster.getName() << "'s armor." << std::endl;
}
else
{
std::cout << "You attack for " << totalDamage
<< " damage!" << std::endl;
// Subtract from monster's hitpoints.
monster.takeDamage(totalDamage);
}
}
else
{
std::cout << "You miss!" << std::endl;
}
std::cout << std::endl;
break;
case 2:
// 25% chance of being able to run.
int roll = Random(1, 4);
if( roll == 1 )
{
std::cout << "You run away!" << std::endl;
return true; //<-- Return out of the function.
}
else
{
std::cout << "You could not escape!" << std::endl;
break;
}
}
}
And here is the Monster::attack function:
void Monster::attack(Player& player)
{
cout << "A " <<mName << " attacks you "
<< "with a " << mWeapon.mName << std::endl;
if( Random(0,20) < mAccuracy )
{
int damage = Random(mWeapon.mDamageRange);
int totalDamage = damage - player.getArmor();
if( totalDamage <= 0 )
{
cout << "The " << mName << "'s attack failed to "
<< "penetrate your armor." << endl;
}
else
{
cout << "You are hit for " << totalDamage
<< " damage!" << endl;
player.takeDamage(totalDamage);
}
}
else
{
cout << "The " << mName << " missed!" << endl;
}
cout << endl;
}
Your Player::attack() method has only one return-statement: return true;. You forgot to add the final line return false; to your method.
This could have easily been prevented if you enable warnings (and pay attention to them!)
Your Player::attack doesn't return in all cases (specifically when it needs to return false). When the calling function tries to access the return value of Player::Attack it will get junk and so you enter the if(ranAway) block and break out of your while loop

Using std::find To Choose An Item From A Vector

I am having an issue getting a vector-based inventory system to work. I am able to list the items in the inventory, but not able to allow a user-selected item to be accessed. Here is the code:
struct aItem
{
string itemName;
int damage;
bool operator==(aItem other)
{
if (itemName == other.itemName)
return true;
else
return false;
}
};
int main()
{
int selection = 0;
aItem healingPotion;
healingPotion.itemName = "Healing Potion";
healingPotion.damage= 6;
aItem fireballPotion;
fireballPotion.itemName = "Potion of Fiery Balls";
fireballPotion.damage = -2;
aItem testPotion;
testPotion.itemName = "I R NOT HERE";
testPotion.damage = 9001;
int choice = 0;
vector<aItem> inventory;
inventory.push_back(healingPotion);
inventory.push_back(healingPotion);
inventory.push_back(healingPotion);
inventory.push_back(fireballPotion);
cout << "This is a test game to use inventory items. Woo!" << endl;
cout << "You're an injured fighter in a fight- real original, I know." << endl;
cout << "1) Use an Item. 2) ...USE AN ITEM." << endl;
switch (selection)
{
case 1:
cout << "Which item would you like to use?" << endl;
int a = 1;
for( vector<aItem>::size_type index = 0; index < inventory.size(); index++ )
{
cout << "Item " << a << ": " << inventory[index].itemName << endl;
a+= 1;
}
cout << "MAKE YOUR CHOICE." << endl << "Choice: ";
cin >> choice;
^^^^
Everything above this line, works. I assume that my problem is the if statement, but I cannot figure out where I am going wrong in my syntax, or if there is a better way to do what I am doing.
if (find(inventory.begin(), inventory.at(choice), healingPotion.itemName) != inventory.end())
cout << "You used a healing potion!";
else
cout << "FIERY BALLS OF JOY!";
break;
case 2:
cout << "Such a jerk, you are." << endl;
break;
}
EDIT: I think I'm not representing this correctly. I need for the player's choice to affect the message displayed. Here's a sample output of the 1st snippet:
Item 1: Healing Potion
Item 2: Healing Potion
Item 3: Healing Potion
Item 4: Potion of Fiery Balls
MAKE YOUR CHOICE.
Choice:
From there, the player can type 1-4, and what I would like is for the number (minus 1, to reflect the vector starting at zero) to be passed to the find, which would then determine (in this small example) if the item at inventory[choice - 1] is a healing potion. If so, display "You used a healing potion!" and if it is not, to display "Fiery balls of joy".
Three problems.
One, Your operator should be declared as:
bool operator==(const aItem& other) const
Two, in this code:
find(inventory.begin(), inventory.at(choice), healingPotion) != inventory.end())
you aren't searching the whole vector from begin() to end() -- you're only searching from begin() to at(choice) where at(choice) points to one-past-the-end of your search set. So you either should do this:
find(&inventory.at(0), &inventory.at(choice), healingPotion) != &inventory.at(choice))
or this...
find(inventory.begin(), inventory.end(), healingPotion.itemName) != inventory.end())
Edit Three, you are trying to compare apples to oranges. You are searching a vector of aItem objects to find a matching aItem object, but the parameter you send to find isn't an aItem object, it is one of the aItem data members.
You should either search for a matching item, like this:
find( inventory.begin(), inventory.end(), healingPotion ) != inventory.end() )
^^^^^^^^
In C++03 you can provide a functor:
#include <functional>
struct match_name : public std::unary_function<aItem, bool>
{
match_name(const string& test) : test_(test) {}
bool operator()(const aItem& rhs) const
{
return rhs.itemName == test_;
}
private:
std::string test_;
};
... and then search for a match using find_if:
find_if( inventory.begin(), inventory.end(), match_name(healingPotion.itemName) ) // ...
In C++11 you can simplify this mess using a closure:
string test = healingPotion.itemName;
if( find_if( inventory.begin(), inventory.end(), [&test](const aItem& rhs)
{
return test == rhs.itemName;
}) == inventory.end() )
{
// not found
}
To add onto John Dibling's answer, the last part is that you are looking for a name, not an aItem.
So it either needs to be:
find(inventory.begin(), inventory.end(), healingPotion) != inventory.end();
where the operator== is defined as:
bool operator==(const aItem& other) const
{
return itemName == other.itemName;
}
Or you need to have your operator== take a string:
find(inventory.begin(), inventory.end(), healingPotion.itemName) != inventory.end();
where the operator== is defined as:
bool operator==(const std::string& name) const
{
return itemName == name;
}
Instead of:
case 1:
cout << "Which item would you like to use?" << endl;
int a = 1;
for( vector<aItem>::size_type index = 0; index < inventory.size(); index++ )
{
cout << "Item " << a << ": " << inventory[index].itemName << endl;
a+= 1;
}
cout << "MAKE YOUR CHOICE." << endl << "Choice: ";
cin >> choice;
if (find(inventory.begin(), inventory.at(choice), healingPotion.itemName) != inventory.end())
cout << "You used a healing potion!";
else
cout << "FIERY BALLS OF JOY!";
break;
case 2:
cout << "Such a jerk, you are." << endl;
break;
}
I neglected to realize that one of the wonders of vectors is the ability to access the value directly- Ryan Guthrie mentioned this in his comment, but I found a simpler "answer". Namely:
case 1:
cout << "Which item would you like to use?" << endl;
//TODO: Learn what the hell the following line actually means.
for( vector<aItem>::size_type index = 0; index < inventory.size(); index++ )
{
//Makes a numerical list.
cout << "Item " << index + 1 << ": " << inventory[index].itemName << endl;
a+= 1;
}
cout << "MAKE YOUR CHOICE." << endl << "Choice: ";
cin >> choice;
//Cannot define this outside of the statement, or it'll initialize to -1
invVecPos = (choice - 1);
//This checks for an invalid response. TODO: Add in non-int checks.
if ((invVecPos) >= inventory.size())
{
cout << "Choice out of bounds. Stop being a dick." << endl;
}
//If the choice is valid, proceed.
else
{
//checking for a certain item type.
if(inventory[invVecPos].itemType == "ITEM_HEALTHPOT")
{
cout << "You used a healing potion!" << endl;
//this erases the potion, and automagically moves everything up a tick.
inventory.erase (inventory.begin() + (invVecPos));
}
else if(inventory[invVecPos].itemType == "ITEM_FIREPOT")
{
cout << "FIERY BALLS OF JOY!" << endl;
}
else
{
//error-handling! Whee!
cout << "Invalid Item type" << endl;
}
}
break;
case 2:
cout << "Why do you have to be so difficult? Pick 1!" << endl;
break;
Thank you, Ryan- with your prodding, I was able to look elsewhere and find the code I needed! The "fixed" code is commented heavily, so anyone else who runs into issues should be able to glean what they need!