Im starting a project with some friends and we have this problem in our inventory system. We're a bit new in c++ and we've been trying to understand the mistake for a little while but still cant find the problem thx in advance.
The probleme seems to be when I used vector.
For some reason once vector is used I get syntax error in the Inventory part and Equip Part.
Sorry if theres grammar error english is'nt my first language
// inventorySysteme.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
#include <vector>
#include <string>
#include <Windows.h>
using namespace std;
struct Item{
string name; // le nom
string purpose; // weapon, armor
int stats; // Dammage, armor point
int attribute; // 0 = rien 1 = armor pearcing 2 = magic dammage ECt.....
};
int main()
{
Item Sword{
"RustedSword", // nom
"Weapon", // weapon
10, // 10 de dammage
1 // armor pearcing
};
Item Staff{
"FirerStaff",
"Weapon",
20,
2
};
string input; // What the player insert
vector<string> Equipment = { "Empty", "Empty", "Empty", "Empty", "Empty", }; // If the place is free
string InventorySlots[] = { "Weapon", "Weapon", "Objec1", "Object2", "Object3" }; // Nom et place inventaire
vector<Item> Inventory = { Sword, Staff }; // inventaire
while (true) {
cin >> input;
if (input == "equipment") {
for (int i = 0; i < 5; i++) {
cout << InventorySlots[i];
if (Equipment[i] == "Empty") {
cout << " " << Equipment[i] << "\n\n";
}
}
}
// Equip Part
if (input == "equip") {
cout << "What would you like to equip?\n";
cin >> input;
for (int i = 0; i < Inventory.size(); i++) {
//Search for item player want to equip and equip it in the right place.
if (input == Inventory[i].name) {
Equipment[Inventory[i].purpose] = Inventory[i].name;
cout << "Successfully equiped!" << endl;
}
}
}
// Inventory Part
if (input == "inventory") {
for (int i = 0; i < Inventory.size(); i++) {
cout << "________________________________________" << endl;
cout << "| " << Inventory[i] << endl;
cout << "| Carried items " << Inventory.size() << " / " << 10 << endl;
cout << "|_______________________________________" << endl;
}
}
if (input == "quit") {
return 0;
}
}
}
Related
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string getItemName(int k) {
if(k == 0) {
return "Sunkist Orange";
} else if(k == 1) {
return "Strawberry";
} else if(k == 2) {
return "papaya";
} else if(k == 3) {
return "Star Fruit";
} else if(k == 4) {
return "Kiwi";
}
return "";
}
int main() {
double prices[] = {2.00, 22.00, 5.00, 6.00, 10.00};
double total = 0.0;
string cart[50];
int key = 0;
int weight = 0;
int index = 0;
cout << "Welcome to Only Fresh Fruit Shop\n\nToday's fresh fruit <Price per Kg>\n";
cout << "0-Sunkist Orange RM2\n";
cout << "1-Strawberry RM22\n";
cout << "2-Papaya RM5\n";
cout << "3-Star Fruit RM6\n";
cout << "4-Kiwi RM10\n";
while (key != -1) {
double current = 0.0;
cout << "Enter fruit code <-1 to stop>: " << endl;
cin >> key;
if (key == -1) {
break;
}
cout << getItemName(key) << endl;
cout << "Enter weight <kg> : " << endl;
cin >> weight;
current = prices[key] + weight;
total = total + current;
}
cout << "-------------------------------------------------------\nReciept\n";
for(int i = 0; i < index; i++) {
cout << cart[i] << "\n";
}
cout << "TOTAL = RM" << total << endl;
return 0;
}
This is my code so far. The system have to display what fruit the user have chosen at in the receipt. My code is not working on the receipt part. Is there any other way on how to improvise the code to make it simpler? How can I improvise?
At very first you can re-organise your data better:
struct Product
{
std::string name;
double price;
};
This struct keeps the data closely related to a single product (fruit in this case) together locally.
You might organise these in an array (preferrably std::array, alternatively raw) making access to simpler – making your getItemName function obsolete entirely. Instead of a static array a std::vector would allow to manage your products dynamically (adding new ones, removing obsolete ones, ...).
You can even use this array to output your data (and here note that your condition in the while loop is redundant; if the inner check catches, the outer one cannot any more as you break before; if the inner one doesn't, the outer one won't either, so prefer a – seeming – endless loop):
std::vector<Product> products({ {"Apple", 2.0 }, { "Orange", 3.0 } });
for(;;)
{
std::cout << "Welcome ... \n";
for(auto i = products.begin(); i != products.end(); ++i)
{
std::cout << i - products.begin() << " - " << i->name
<< " RM " << i-> price << '\n';
}
// getting key, exiting on -1
if(0 <= key && key < products.size()
{
// only now get weight!
}
else
{
std::cout << "error: invalid product number" << std::endl;
}
}
Now for your cart you might just add indices into the vector or pointers to products – note, though, that these will invalidate if you modify the vector in the mean-time – if you do so you need to consider ways to correctly update the cart as well – alternatively you might just empty it. Inconvenient for the user, but easy to implement…
In any case, such a vector of pointers to products would easily allow to add arbitrary number of elements, not only 50 (at least as much as your hardware's memory can hold...) and would allow for simple deletion as well.
Calculating the full price then might occur only after the user has completed the cart:
// a map allows to hold the weights at the same time...
std::map<Product*, weight> cart;
for(;;)
{
// ...
if(0 <= key && key < products.size()
{
double weight;
std::cin >> weight;
// TODO: check for negative input!
// (always count with the dumbness of the user...)
cart[&products[key]] += weight;
// note: map's operator[] adds a new entry automatically,
// if not existing
}
}
Finally you might iterate over the cart, printing some information and calculating total price for the shopping cart:
double total = 0.0;
for(auto& entry : cart) // value type of a map always is a std::pair
{
std::cout << entry.first->name << "..." << entry.second << " kg\n";
total += entry.first->price * entry.second;
// note: you need MULTIPLICATION here, not
// addition as in your code!
}
std::cout << "Total price: RM " << total << std::endl;
This should do it whilst staying close to original code, I also improved you're method of gathering price/name a bit, try to catch the out of index exceptions or check if current index is NULL. Good luck!
#include <iostream>
#include <string>
#include <sstream>
#include <vector>;
using namespace std;
std::vector<std::string> itemList = {"Sunkist Orange", "Strawberry", "Papaya", "Star Fruit", "Kiwi"};
//If you dont want this to be global put it in the getItemName function
string getItemName(int k) {
return itemList.at(k);
}
int main() {
std::vector<double> prices = { 2.00, 22.00, 5.00, 6.00, 10.00 };
double total = 0.0;
int key = 0, weight = 0;
cout << "Welcome to Only Fresh Fruit Shop\n\nToday's fresh fruit <Price per Kg>\n";
cout << "0-Sunkist Orange RM2\n";
cout << "1-Strawberry RM22\n";
cout << "2-Papaya RM5\n";
cout << "3-Star Fruit RM6\n";
cout << "4-Kiwi RM10\n";
while (key != -1) {
double current = 0.0;
cout << "Enter fruit code <-1 to stop>: " << endl;
cin >> key;
if (key == -1) {
break;
}
cout << getItemName(key) << endl;
cout << "Enter weight <kg> : " << endl;
cin >> weight;
current += prices.at(key) + weight;
total += total + current;
cout << "-------------------------------------------------------\nReciept\n";
cout << "Purchased: " << getItemName(key) <<" "<< "TOTAL = RM" << total << "\n" << endl;
}
return 0;
}
I noticed there is a string cart[50] and int index = 0which you did not use throuoght the whole code except printing it at the end of the code. I am guessing that you want to add the fruit into the cart but it seems like you have not done so.
double price[50];
while (key != -1) {
double current = 0.0;
cout << "Enter fruit code (<-1> to stop): ";
cin >> key;
if (key == -1) break;
cout << getItemName(key) << endl;
cout << "Enter weight <kg> : ";
cin >> weight;
cart[index] = getItemName(key);
price[index] = prices[key] * weight;
total += price[index];
index++;
}
for (int i = 0; i < index; i++) {
cout << cart[i] << " " << price[i] << endl;
}
I have added some code so that cart[index] = getItemName(key). When you print each element of cart, it will now work. Also, current = prices[key] * weight is the correct one, not addition (unless your rules are different).
on a side note are you malaysian
I'm working on a program that I've seen other people do online except I'm trying to use functions to complete it to make it somewhat more challenging for me to help me better understand pointers and vectors. The problem I'm having in xcode is I keep getting this error..
Expected ';' after top level declarator
right here on my code,
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers) //<<< Error
{
cout << fixed << setprecision(2);
...
Where I am trying to use vector numbers in my function. Basically I want the numbers from the function passed back so that I can use them in another function I have not created yet. I've googled this error and it seems like no one can give a straight answer on how to fix this problem. Is anyone familiar with how to correct this? By no means is this code finished I'm just trying to get information regarding vectors as a parameter because from what I'm seeing syntax wise on other sites it looks to be correct. Thanks for your feedback.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
struct menuItemType{
string menuItem;
double menuPrice;
};
void getData(menuItemType (&mlist)[8]);
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
int main() {
vector<int> temp;
menuItemType menuList[8];
getData(menuList);
showMenu(menuList,temp);
/*
cout << menuList[0].menuItem << " " << menuList[0].menuPrice << endl;
cout << menuList[1].menuItem << " " << menuList[1].menuPrice << endl;
*/
return 0;
}
void getData(menuItemType (&mlist)[8]){
string Str;
ifstream infile;
infile.open("cafe135.txt");
if(infile.is_open())
{
for (int i = 0; i < 8; ++i){
infile >> mlist[i].menuItem >> mlist[i].menuPrice;
}
}
else cout << "Unable to open file";
}
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
{
cout << fixed << setprecision(2);
string choice;
cout << "Would you like to view the menu? [Y] or [N]: ";
cin >> choice;
cout << endl;
int x = 3;
int count = 1;
while (choice != "Y" && choice != "N" && choice != "y" && choice != "n")
{
if (count == 4){
return;
}
cout << "Error! Please try again ["
<< x
<< "] selections remaining: ";
cin >> choice;
cout << endl;
x--;
count++;
}
if (choice == "N" || choice == "n"){
return;
}
else
{
cout << "___________ Breakfast Menu ___________" << endl;
for (int i = 0; i < sizeof(menu_List)/sizeof(menu_List[0]); ++i)
{
cout << "Item "
<< (i+1)
<< ": "
<< menu_List[i].menuItem
<< " "
<< menu_List[i].menuPrice
<< endl;
}
cout << endl;
string itemSelection = " ";
//int str_length = 0;
cout << "Select your item numbers separated"
<< " by spaces (e.g. 1 3 5) Select 0 to cancel order: ";
cin.ignore();
getline(cin, itemSelection);
if (itemSelection == "0")
{
return;
}
vector<int> vectorItemSelection;
stringstream text_stream(itemSelection);
string item;
while (getline(text_stream, item, ' '))
{
vectorItemSelection.push_back(stoi(item));
}
int n = vectorItemSelection.size();
int arr[n];
for (int i = 0; i < n; i++)
{
arr[i] = vectorItemSelection[i];
}
}
}
Compare how menu_List is declared in this line
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
and this line
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
The first one is correct.
But I have to agree with the comments above, you are mixing up a lot of different things here. Just use vectors, 99% of the time it's the right thing to do anyway. and it's easier to learn one thing at a time.
Prefer to write your code like this
void getData(vector<menuItemType>&);
void showMenu(vector<menuItemType>&, vector<int> numbers);
int main() {
vector<int> temp;
vector<menuItemType> menuList(8);
...
See? Just use vectors everywhere.
This is part of a homework assignment I recently finished. I am required to use an array of structs to store a library of books by title and author. The code is working and running perfectly fine when sorting and displaying author or title alphabetically according to user input.
The only issue I run into is when it shows all books sorted alphabetically. There are 14 books total in the text file used with the assignment, but only 13 books show up when the show all (S) option is entered.
An example of the error would be:
()
Audio for Games (Brandon)
Instead of:
Audio for Games (Brandon)
Beginning LINUX Programming (Stones and Matthew)
My Code:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
// structure
struct Book {
string title;
string author;
};
const int ARRAY_SIZE = 1000;
Book books[ARRAY_SIZE];
string pathName;
ifstream lib;
// global variables
int loadData();
void showAll(int count);
void sortByTitle(int count, string title);
int main()
{
// initialised variables
int count = 0;
char selector = 'q', yesNoAnswer = 'n';
string name;
string title;
// asks user for file pathname
cout << "Welcome to Tommy's Library Database." << endl;
cout << "Please enter the name of the file: ";
getline(cin, pathName);
loadData();
count = loadData();
cout << count << " Records loaded successfully." << endl;
// Switch case menu
do {
cout << endl << "Please enter a keyword that corresponds to the list of options: " << endl;
cout << " Search by: (A)uthor, (T)itle, (S)how All, (Q)uit Program: ";
cin >> selector;
selector = toupper(selector);
switch (selector)
{
case 'S':
sortByTitle(count, title);
if (count <= 0) {
cout << " No counts found! " << endl;
}
else {
showAll(count);
}
break;
}
}
while (selector != 'q' && selector != 'Q');
return 0;
}
int loadData()
{
int count = 0;
int i = 0;
lib.open(pathName);
ifstream lib(pathName);
if (!lib)
{
cout << " Unable to open file path! " << endl;
return -1;
}
while (!lib.eof())
{
getline(lib, books[count].title);
getline(lib, books[count].author);
count++;
}
return count;
}
// displays all book titles beside the author names
void showAll(int count)
{
for (int i = 0; i < count; i++)
{
cout << books[i].title << " " << "(" << books[i].author << ")" << endl;
}
}
// Sorts by book title.
void sortByTitle(int count, string title) {
Book temp;
for (int i = 0; i < count; i++) {
for (int j = 0; j < count - i; j++) {
if (books[j].title > books[j + 1].title) {
temp = books[j];
books[j] = books[j + 1];
books[j + 1] = temp;
}
}
}
}
The text file im using with the assignment (books.txt)
Objects First with Java
Barnes and Kolling
Game Development Essentials
Novak
The Game Maker's Apprentice
Overmars
C++ Programming: From Problem Analysis...
Malik
C++ Programming Lab Manual
Scholl
Beginning LINUX Programming
Stones and Matthew
C++ Programming: Program Design Including...
D. S. Malik
C++ How to Program
Deitel and Deitel
Programming and Problem Solving with C++
Dale, Weems, Headington
Game Character Development with Maya
Ward
Developing Games in Java
Brackeen
C# Programming
Harvey, Robinson, Templeman, Watson
Java Programming
Farrell
Audio for Games
Brandon
You were starting your loop from 0 inside your showAll() method when your books array starts from 1, just start the loop from 1 and go to count + 1
for (int i = 1; i < count + 1; i++)
Your sort function doesn't work correctly. It's off by one and moves an empty element to the first index. It would cause undefined behavior if your array were full. Your sort function sorts all elements from 0 to count but it should sort from 0 to count - 1. You should fix your sort function (std::sort usually is faster than bubble sort):
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
// structure
struct Book {
string title;
string author;
};
const int ARRAY_SIZE = 1000;
Book books[ARRAY_SIZE];
string pathName;
ifstream lib;
// global variables
int loadData();
void showAll(int count);
void sortByTitle(int count, string title);
int main()
{
// initialised variables
int count = 0;
char selector = 'q', yesNoAnswer = 'n';
string name;
string title;
// asks user for file pathname
cout << "Welcome to Tommy's Library Database." << endl;
cout << "Please enter the name of the file: ";
getline(cin, pathName);
loadData();
count = loadData();
cout << count << " Records loaded successfully." << endl;
// Switch case menu
do {
cout << endl << "Please enter a keyword that corresponds to the list of options: " << endl;
cout << " Search by: (A)uthor, (T)itle, (S)how All, (Q)uit Program: ";
cin >> selector;
selector = toupper(selector);
switch (selector)
{
case 'S':
sortByTitle(count, title);
if (count <= 0) {
cout << " No counts found! " << endl;
}
else {
showAll(count);
}
break;
}
}
while (selector != 'q' && selector != 'Q');
return 0;
}
int loadData()
{
int count = 0;
int i = 0;
lib.open(pathName);
ifstream lib(pathName);
if (!lib)
{
cout << " Unable to open file path! " << endl;
return -1;
}
while (!lib.eof())
{
getline(lib, books[count].title);
getline(lib, books[count].author);
count++;
}
return count;
}
// displays all book titles beside the author names
void showAll(int count)
{
for (int i = 0; i < count; i++)
{
cout << books[i].title << " " << "(" << books[i].author << ")" << endl;
}
}
// Sorts by book title.
void sortByTitle(int count, string title) {
std::sort(books, books + count, [](const auto &lhs, const auto &rhs) {
return lhs.title < rhs.title;
});
}
In addition:
You shouldn't read a stream with while (!lib.eof()): Why is iostream::eof inside a loop condition (i.e. while (!stream.eof())) considered wrong?
You can remove the first loadData()
You can remove the second parameter of void sortByTitle(int count)
You are shadowing global variables with local variables, e.g. global ifstream lib and local ifstream lib in int loadData()
You can remove unused variables
You should remove using namespace std;: Why is “using namespace std;” considered bad practice?
You should avoid global variables
You should replace endl by '\n' if you don't need to flush in that moment. endl does more than a simple linebreak and usually it's not necessary.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using std::cin;
using std::cout;
using std::ifstream;
using std::string;
// structure
struct Book {
string title;
string author;
};
const int ARRAY_SIZE = 1000;
// global variables
int loadData(string pathName, Book *books);
void showAll(Book *books, int count);
void sortByTitle(Book *books, int count);
int main()
{
// initialised variables
int count = 0;
char selector = 'q';
// asks user for file pathname
cout << "Welcome to Tommy's Library Database.\n";
cout << "Please enter the name of the file: ";
string pathName;
getline(cin, pathName);
Book books[ARRAY_SIZE];
count = loadData(pathName, books);
cout << count << " Records loaded successfully.\n";
// Switch case menu
do {
cout << "\nPlease enter a keyword that corresponds to the list of options: \n";
cout << " Search by: (A)uthor, (T)itle, (S)how All, (Q)uit Program: ";
cin >> selector;
selector = toupper(selector);
switch (selector)
{
case 'S':
sortByTitle(books, count);
if (count <= 0) {
cout << " No counts found! \n";
}
else {
showAll(books, count);
}
break;
}
}
while (selector != 'q' && selector != 'Q');
return 0;
}
int loadData(string pathName, Book *books)
{
int count = 0;
ifstream lib(pathName);
if (!lib)
{
cout << " Unable to open file path! \n";
return -1;
}
while (getline(lib, books[count].title))
{
getline(lib, books[count].author);
count++;
}
return count;
}
// displays all book titles beside the author names
void showAll(Book *books, int count)
{
for (int i = 0; i < count; i++)
{
cout << books[i].title << " " << "(" << books[i].author << ")\n";
}
}
// Sorts by book title.
void sortByTitle(Book *books, int count) {
std::sort(books, books + count, [](const auto &lhs, const auto &rhs) {
return lhs.title < rhs.title;
});
}
I am currently working on the assignment where I need to iterate through some student records. Each record has reg. number, name, and 0 to multiple module names with marks respectively.
I have a Student class and a Main class.
In the main class there's a function to iterate through a vector of Students and print the average grade.
Function to print average grades as well as names.
void aboveGiven(vector<Student> &students, float given) {
vector<Student>::iterator it;
for(it = students.begin(); it != students.end(); it++) {
if(it -> getAverageMark() >= given) {
cout << it->getName() << " " << setprecision(2) << it->getAverageMark() << endl;
}
}
}
Function to calculate average grade. "Given" parameter is the input used to define above what average to display the records. (in this case it is 70 meaning all the records with average above 70 have to be printed)
float Student::getAverageMark() const
{
if (marks.size() == 0)
return 0;
int count;
float sum;
map<string, float>::const_iterator it;
for (it = marks.begin(); it != marks.end(); ++it, ++count) {
sum += it->second;
}
return sum / count;
}
The massive problem I have is weird behaviour of cout where it prints nothing if I pass 60 or above as a "Given" parameter.
However the following code:
void aboveGiven(vector<Student> &students, float given) {
vector<Student>::iterator it;
for(it = students.begin(); it != students.end(); it++) {
cout << "a" << endl;
if(it -> getAverageMark() >= given) {
cout << it->getName() << " " << setprecision(2) << it->getAverageMark() << endl;
}
}
}
with only difference of line cout << "a" << endl;gives me following output:
a
a
a
Lisa Simpson 88.03
a
Homer Simpson 99.90
a
a
Wayne Rooney 75.45
a
a
a
a
Where 'a' corresponds to all the records with average grade below 70 and, as we can see all the records with average grade above 70 are now printed well.
Sometimes, when using different parameters for cout, only some of the outputs would be actually displayed but not all.
I am new to C++ and still am very confused with references and pointers, so I suspect there might be a problem with them. Otherwise could this be an issue with IDE ( I am using CLion which supports C++11).
I am sorry if this is not informative enough, have never posted anything here before. If you need any additional information please feel free to ask, I will post it.
classes just in case:
Student.cpp
using namespace std;
#include "Student.h"
#include <iostream>
Student::Student(const string& name, int regNo)
: Person(name)
{
this->name = name;
this->regNo = regNo;
this->marks = marks;
}
int Student::getRegNo() const
{
return regNo;
}
void Student::addMark(const string& module, float mark)
{
marks[module] = mark;
}
float Student::getMark(const string& module) throw(NoMarkException)
{
if (marks.find(module) == marks.end()) {
throw NoMarkException();
}
return marks[module];
}
float Student::getAverageMark() const
{
if (marks.size() == 0)
return 0;
int count;
float sum;
map<string, float>::const_iterator it;
for (it = marks.begin(); it != marks.end(); ++it, ++count) {
sum += it->second;
}
cout << fixed;
return sum / count;
}
And main: (at the moment it is really bad styled, sorry)
using namespace std;
#include <iostream>
#include <fstream>
#include <sstream>
#include "Student.h"
#include <vector>
#include <iomanip>
void aboveGiven(vector<Student>& students, float given)
{
vector<Student>::iterator it;
for (it = students.begin(); it != students.end(); it++) {
cout << "a" << endl;
if (it->getAverageMark() >= given) {
cout << it->getName() << " " << setprecision(2) << it - > getAverageMark() << endl;
}
}
}
int main()
{
char studentFileName[30];
char marksFileName[30];
vector<Student> students;
cout << "Enter the name of a file with Students: " << endl;
cin >> studentFileName;
ifstream studentFile;
string line;
studentFile.open(studentFileName, ios::in);
if (studentFile.is_open()) {
while (getline(studentFile, line)) {
istringstream iss(line);
int regn;
string firstName, lastName;
iss >> regn >> firstName >> lastName;
students.push_back(Student(firstName + " " + lastName, regn));
}
studentFile.close();
}
else {
cout << "Failed to open: " << studentFileName << endl;
}
cout << "Enter the name of a file with Marks: " << endl;
cin >> marksFileName;
ifstream marksFile;
string ln;
marksFile.open(marksFileName, ios::in);
if (marksFile.is_open()) {
while (getline(marksFile, ln)) {
int regn;
string module;
float mark;
bool studentFound = false;
istringstream iss(ln);
iss >> regn >> module >> mark;
for (auto& student : students) {
if (student.getRegNo() == regn) {
student.addMark(module, mark);
studentFound = true;
}
}
if (!studentFound) {
cout << "Student with Registration Number " << regn << was not found." << endl;
}
}
marksFile.close();
}
else {
cout << "Failed to open: " << marksFileName << endl;
}
for (auto& student : students) {
map<string, float> tempMap = student.getMarks();
map<string, float>::iterator it;
cout << setw(20) << student.getName() << ": ";
if (tempMap.size() == 0) {
cout << "N/A";
}
else {
for (it = tempMap.begin(); it != tempMap.end(); it++) {
cout << setw(5) << it->first << '(' << it->second << "); ";
}
}
cout << endl;
}
aboveGiven(students, 70);
}
Thanks in advance for your help!
You didn't initialize int sum and int count in Student::getAverageMark. Then no one knows what could they be. They must be int sum = 0; and int count = 0;
I'm building text-rpg inventory system but I'm not really sure how to properly create equipable items.
For example, I can equip item which is in player inventory but I cannot identify what kind of item that is(Sword, Shield, Gloves or something else..) because item should be equiped in proper place(Helmet on head, sword in hands and so on).
Is there any way to do so?
#include <iostream>
#include <vector>
#include <Windows.h>
#include <string>
using namespace std;
void Red()
{
SetConsoleTextAttribute
(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_INTENSITY);
} //Intensive red console text color.
void Green()
{
SetConsoleTextAttribute
(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY);
} //Intensive green console text color.
void Normal()
{
SetConsoleTextAttribute
(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE);
} //Default console text color.
struct Item{
string name; //Item name.
int price; //Item price.
int purpose; // 0 - Head, 1 - Neck, 2 - Torso, 3 - Hands, 4 - Legs, 5 - Feets.
int attribute; //Attack, Defense...
};
int main()
{
//Isn't the smartest way to do so...
Item Sword{
"Sword", //This item name is 'Short Sword'.
87, //Cost 87 gold pieces.
3, //Use this item with hands. :D.
10 //+10 attack.
};
string input; // input is for player commands.
vector<string> Equipment = { "<Empty>", "<Empty>", "<Empty>", "<Empty>", "<Empty>","<Empty>" }; //Current equipment.
vector<string> Inventory = {Sword.name}; //Player Inventory.
string InventorySlots[] = { "Head", "Neck", "Torso", "Hands", "Legs", "Feets" }; //Player parts where items can be equiped.
while (true){
cin >> input;
if (input == "equipment"){
for (int i = 0; i < 6; i++){
Normal();
cout << InventorySlots[i];
if (Equipment[i] == "<Empty>")
Red();
cout << " " << Equipment[i] << endl << endl;
}
Normal();
}
if (input == "equip"){
cout << "What do you want to equip? ";
cin >> input;
for (int i = 0; i < Inventory.size(); i++){
//Search for item player want to equip and equip it in the right place.
if (input == Inventory[i]){
//Inventory[i] = input;
//But how to identify what kind of item it is?
cout << "Successfully equiped!" << endl;
}
}
}
if(input == "inventory"){
for (int i = 0; i < Inventory.size(); i++){
cout << "______________________________________________________________" << endl;
cout << "| " << Inventory[i] << endl;
cout << "| Carried items " << Inventory.size() << " / " << 20 << endl;
cout << "|_____________________________________________________________" << endl;
}
}
}
system("PAUSE"); // or 'cin.get()'
return 0;
}
There are plenty of possibilities to do that.
Simple approach
First, you have to keep an inventory of items, not of strings:
vector<Item> Inventory = {Sword, Helmet}; //Player Inventory.
Then you have to seacrh using Inventroy[i].name and use inventory[i].purpose to find the right slot:
for(int i = 0; i < Inventory.size(); i++){
//Search for item player want to equip and equip it in the right place.
if(input == Inventory[i].name){
Equipment[Inventory[i].purpose] = Inventory[i].name;
cout << "Successfully equiped!" << endl;
}
}
Slight improvements
Note that for the next improvement of your game, you'll experience a similar problem with your equipement: as it is a vector of strings, you won't get a direct access to the item's properties, such as the effect on attack or defense the equipment has.
Therefore you should also make Equipment a vector<Item>:
Item Empty{"<Empty>", 0, 0, 0};
vector<Item> Equipment{6, Empty}; //Current equipment: 6 x Empty.
...
You could also consider making Inventory a map<string, Item> for easy access by name