C++ Player Creation Menu - c++

I am trying to make a text based C++ game.
I have a player class set up and I am now working on a method inside that class called displayMenu(), which will ask the user a variety of questions based on their player and send the data to the main/client code and then that data will create an object of player class via a constructor of player class.
My main question is...
I am trying to compare the input (string) from the user to the (string) they need to inputting, but I am getting an error which says "lower()" can not be resolved. I believe you have to compare each character, but I think there may be a more effective way to code this to provide simplicity and readability. What exactly am I doing wrong? What is the best way to code this?
Here is my code...
void Player::displayMenu(std::string& PlaName, std::string& cName, int& lvl, int& HP)
{
std::cout << "Player Creation Menu" << std::endl;
std::cout << "====================" << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << "What is your name? " << std::endl;
std::cin >> PlaName;
std::cout << "What is your specitality? " << std::endl;
std::cin >> cName;
while(cName.lower() != "brawler" || cName.lower() != "thief" || cName.lower() != "persuader" || cName.lower()
!= "gunman")
{
std::cout << "That is not your true specitality..." << std::endl;
std::cout << "You must pick from { 'Brawler', 'Thief' , 'Persuader', 'Gunman' }" << std::endl;
std::cin >> cName;
}
}

I have several remarks on your original code:
Reading and comparing the strings seems like a bit complicated for this use-case. It is common to see usage of first character as identifier, to make it simpler.
The specialty is a classic example for enum (or enum class, which is enum that you must use always with it's name)
The displayMenu method should not be part of the Player class, since it isn't a behavior (an action) of the player. It should be part of the "Game"/"UI" class.
If you really want to use the complete string in order to identify the specialty, you can use the code examples in the first answer in the link Ayxan put in the comments.
Here is my proposed code:
#include <iostream>
constexpr char INVALID_CHARACTER_INPUT = '#';
enum class CharacterSpecialty
{
BRAWLER,
THIEF,
PERSUADER,
GUNMAN,
NUM_OF_SPECIALITY_TYPES
};
`
class Player
{
public:
Player(const std::string& player_name, CharacterSpecialty char_specialty) :
name(player_name),
specialty(char_specialty)
{
}
private:
std::string name;
CharacterSpecialty specialty;
};
Player displayMenuAndCreatePlayer()
{
std::cout << "\nPlayer Creation Menu\n" << "====================\n\n" << std::endl;
std::cout << "Enter your name: " << std::endl;
std::string player_name{};
std::cin >> player_name;
CharacterSpecialty char_specialty = CharacterSpecialty::NUM_OF_SPECIALITY_TYPES;
while(char_specialty == CharacterSpecialty::NUM_OF_SPECIALITY_TYPES)
{
std::cout << "What is your specialty?\n" << "[B]rawler, [T]hief, [P]ersuader or [G]unman"<< std::endl;
std::string char_type_input;
std::cin >> char_type_input;
char input = char_type_input.size() == 1 ? char_type_input[0] : INVALID_CHARACTER_INPUT;
switch(char_type_input)
{
case 'b':
case 'B':
char_specialty = CharacterSpecialty::BRAWLER;
break;
case 't':
case 'T':
char_specialty = CharacterSpecialty::THIEF;
break;
case 'p':
case 'P':
char_specialty = CharacterSpecialty::PERSUADER;
break;
case 'g':
case 'G':
char_specialty = CharacterSpecialty::GUNMAN;
break;
default:
std::cout << "Invalid Specialty Entered!\n" << std::endl;
break;
}
}
return Player(player_name, char_specialty);
}
int main()
{
Player player = displayMenuAndCreatePlayer();
}

Related

Switch statement and user input in C++

I am having some trouble using a switch statement with user input. Can anyone please explain what is going on? I am sorry if this is a noob question as I'm very used to Python and just started learning C++.
#include <iostream>
#include <string>
using namespace std;
#include <cstdlib>
int main()
{
string name;
cout << "Enter a name: ";
cin >> name;
switch (name){
case name == "Seth":
std::cout << "That's my name!";
return 0;
break;
case name == "seth":
std::cout << "Wow, you couldnt even put correct capitalization on my name...\n";
std::cout << "LEARN YOUR PRONOUNS AND GO BACK TO SCHOOL!";
return 0;
break;
case name == "SETH":
std::cout << "Ok ok you spelled my name right but make sure you turn off caps lock please";
return 0;
break;
default:
std::cout << "Come on get my name RIGHT!!!\n";
std::cout << "But you entered " << name;
}
return 0;
}
According to the C++ 17 Standard (9.4.2 The switch statement)
2 The condition shall be of integral type, enumeration type, or class
type. If of class type, the condition is contextually implicitly
converted (Clause 7) to an integral or enumeration type. If the
(possibly converted) type is subject to integral promotions (7.6), the
condition is converted to the promoted type. Any statement within the
switch statement can be labeled with one or more case labels as
follows: case constant-expression : where the constant-expression
shall be a converted constant expression (8.20) of the adjusted type
of the switch condition. No two of the case constants in the same
switch shall have the same value after conversion.
The class std::string does not have an implicit conversion operator that converts an object of the type std::string to an integral or enumeration type.
So the expression in this switch statement
switch (name){
is invalid.
Also case labels like this
case name == "seth":
are syntactically incorrect.
You could resolve your problem with the switch statement for example the following way
#include <iostream>
#include <string>
#include <array>
#include <iterator>
#include <algorithm>
int main()
{
std::array<const char *, 3> names =
{
"Seth", "seth", "SETH"
};
std::string name;
std::cout << "Enter a name: ";
std::cin >> name;
size_t n = std::find( std::begin( names ), std::end( names ), name ) -
std::begin( names );
switch (n)
{
case 0:
std::cout << "That's my name!";
break;
case 1:
std::cout << "Wow, you couldnt even put correct capitalization on my name...\n";
std::cout << "LEARN YOUR PRONOUNS AND GO BACK TO SCHOOL!";
break;
case 2:
std::cout << "Ok ok you spelled my name right but make sure you turn off caps lock please";
break;
default:
std::cout << "Come on get my name RIGHT!!!\n";
std::cout << "But you entered " << name;
break;
}
}
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Enter a name: ";
std::cin >> name;
if(name == "Seth")
{
std::cout << "That's my name!" << std::endl;
}
else if(name == "seth")
{
std::cout << "Wow, you couldn't even put correct capitalization on my name..." << std::endl;
std::cout << "LEARN YOUR PRONOUNS AND GO BACK TO SCHOOL!" << std::endl;
}
else if(name == "SETH")
{
std::cout << "Ok ok you spelled my name right but make sure you turn off caps lock please" << std::endl;
}
else
{
std::cout << "Come on get my name RIGHT!!!" << std::endl;
std::cout << "But you entered " << name << std::endl;
}
return 0;
}
As other people have told that you can not do string comparison in switch and provided a solution. But I would like to use enum class which I found more readable and int comparison much more faster than string comparison.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <unordered_map>
int main() {
enum class Spellings { Seth, seth, SETH };
const std::unordered_map<std::string, Spellings> spellings_map{
{"Seth", Spellings::Seth},
{"seth", Spellings::seth},
{"Seth", Spellings::SETH},
};
std::string name;
std::cout << "Enter a name: ";
std::cin >> name;
auto result = spellings_map.find(name);
if (result == spellings_map.end()) {
std::cout << "Come on get my name RIGHT!!!\n";
std::cout << "But you entered " << name;
return -1;
}
switch (result->second) {
case Spellings::Seth:
std::cout << "That's my name!";
break;
case Spellings::seth:
std::cout << "Wow, you couldnt even put correct capitalization on "
"my name...\n";
std::cout << "LEARN YOUR PRONOUNS AND GO BACK TO SCHOOL!";
break;
case Spellings::SETH:
std::cout << "Ok ok you spelled my name right but make sure you "
"turn off caps lock please";
break;
}
}

Static vector as a class objects container

I've seen many questions and answers about this issue but still I can't solve my problem. How should I initialize a static vector? I'm also asking you for checking I use a default construct properly. I don't mean checking if it's working because I know that it does. I just wonder if it is an elegant implementation?
class Employee
{
private:
static std::vector<Employee> employee;
std::string name;
int age;
Employee::Employee()
{
std::string localName;
int localAge;
std::cout << "So... do you want to hire a new employee? Let's look at CVs " << std::endl;
localName = "Marek"; //GenerateName();
localAge = 21; //these function is not ready yet. it'd be just a rand()
std::cout << "I've got one. What do u think about " << localName << " age " << localAge << "?" << std::endl;
int decision;
do
{
std::cout << "Do you want hire him [1] or not [2] ? " << std::endl;
std::cin >> decision;
switch (decision)
{
case 1:
name = localName;
age = localAge;
decision = 0;
break;
case 2:
employees.erase(employees.end());
decision = 0;
break;
default:
std::cout << "Incorrect option. Try again" << std::endl;
}
} while (decision != 0);
}
public:
static void Employ()
{
employees.push_back(Employee::Employee());
}
};
int main()
{
Employee::Employ();
system("pause");
}
Your code didn't work when I ran it. In addition to adding includes and fixing some typos, I had to add this line:
std::vector<Employee> Employee::employee;
However, I don't think this is the best solution. For sweet clarity's sake, an Employee shouldn't contain a vector of Employees, but should be, well, an employee. If you want a vector of employees, you can declare one in main (or elsewhere). If you want your vector of employees to have some added features like the interactive employee-adding function you wrote, you can do it like this:
class EmployeeForce: public std::vector<Employee>
{
void interactivelyAddEmployee ();
...
};
...
EmployeeForce myStaff;
I've changed entire the concept. The problem was that I unnecessary wanted to put inside the class the container of objects (in this case: std::vector). I know now that class should only contain informations about the single object; it shouldn't know about anything about others one.
class Employee
{
public:
std::string name;
int age;
};
std::ostream& operator<<(std::ostream& out, const std::vector<Employee>& v)
{
out << "[";
for (size_t i = 0; i < v.size(); ++i)
{
out << "Name: " << v[i].name << " age: " << v[i].age;
if (i != v.size() - 1)
out << ", ";
}
out << "]";
return out;
}
Employee generate_random_employee(Employee obj)
{
obj.name = "Marek"; //GenerateName();
obj.age = 21; //these function is not ready yet. it'd be just a rand()
return obj;
}
int main()
{
int decision;
std::string name;
std::vector<Employee> employees;
Employee some_new_employee;
std::cout << "Welcome mrs. manager. What do you want to do today, sir?" << std::endl << std::endl;
do
{
std::cout << "Hire sombody [1], Fire somebody [2], Exit [0] " << std::endl;
std::cin >> decision;
switch (decision)
{
case 1:
some_new_employee = generate_random_employee(some_new_employee);
if (should_i_employ(some_new_employee))
{
employees.push_back(some_new_employee);
}
break;
case 2:
std::cout << "Who do you want to fire?" << std::endl;
std::cin >> name;
if (is_the_employee_exist(employees, name))
{
if (are_u_sure())
{
}
}
else
std::cout << "" << std::endl;
break;
case 3:
std::cout << employees << std::endl;
break;
case 0:
std::cout << "Good bye, sir" << std::endl;
break;
default:
std::cout << "There is not these option. Try again " << std::endl;
}
} while (decision != 0);
system("pause");
}

Returning an integer to determine which switch statement to show

I'm creating a board game (stratego) in c++ and was wondering if it considered a poor practice to return an integer from a class method in order to determine which case in a switch statement to show to the user.
Example:
In stratego, you can't attack board pieces that are part of your own army so I have a message "You cannot attack your own army" when the user tries to do so.
Same thing if a movement is performed that would result in the player jumping off the board, moving too many spaces, etc.
Each of these invalid movements has it's own unique message, but to avoid printing them from the Class.cpp file, which is where the player's moves are validated, I have the Class.cpp file returning an integer to a switch statement in the main() that it was called from.
What is the most recommended way to handle how the messages get called?
class Test
{
public:
Test()
{
}
int Validate_Move(int valid)
{
if (valid > 0 && valid < 5)
{
return 1;
}
else if (valid > 5)
{
return 2;
}
}
};
int main()
{
int entry;
std::cout << "Enter move: ";
std::cin >> entry;
Test obj;
switch (obj.Validate_Move(entry))
{
case 1:
std::cout << "Move is valid" << std::endl;
case 2:
std::cout << "Move is invalid" << std::endl;
default:
std::cout << "Error occured" << std::endl;
}
return 0;
}
There's nothing wrong with that technique. If you want to be more explicit, you could always make an enum
class Test
{
public:
Test() = default;
enum EValidity {eError, eValid, eInvalid};
EValidity Validate_Move(int valid)
{
if (valid > 0 && valid < 5)
{
return eValid;
}
else if (valid > 5)
{
return eInvalid;
}
else
{
return eError;
}
}
};
int main()
{
int entry;
std::cout << "Enter move: ";
std::cin >> entry;
Test obj;
switch (obj.Validate_Move(entry))
{
case Test::eValid:
std::cout << "Move is valid" << std::endl;
break;
case Test::eInvalid:
std::cout << "Move is invalid" << std::endl;
break;
case Test::eError:
std::cout << "Error occured" << std::endl;
break;
default:
assert(false);
}
return 0;
}

String Game, creating a specific Loop? 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.

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!