~Inventory() {
items.clear();
}
void addItem(std::string itemName, int quantity, double itemPrice) {
for (auto& item : items) {
if (item.name == itemName) {
item.quantity += quantity;
std::cout << "Successfully updated quantity of item!" << std::endl;
if (itemPrice > 0.0) {
item.price = itemPrice;
std::cout << "Successfully updated price of item!" << std::endl;
}
displayItem(itemName);
return;
}
}
items.push_back(Item(itemName, quantity, itemPrice));
itemCount++;
std::cout << "Successfully added item!" << std::endl;
displayItem(itemName);
}
void removeItem(std::string itemName, int quantity) {
for (auto it = items.begin(); it != items.end(); ++it) {
if (it->name == itemName) {
if (quantity == 0 || quantity >= it->quantity) {
items.erase(it);
itemCount--;
std::cout << itemName << " has been successfully removed from the inventory." << std::endl;
return;
}
if (it->quantity < quantity) {
std::cout << "You specified to delete " << quantity << " of " << itemName << ", but there are only " << it->quantity << " left!" << std::endl;
std::cout << "Please specifiy fewer items, or leave quantity field blank to delete all." << std::endl;
return;
}
it->quantity = quantity;
std::cout << "Successfully removed " << quantity << " of " << itemName << "!" << std::endl;
displayItem(itemName);
return;
}
}
std::cout << itemName << " was not found in the inventory. Please check spelling or try again later." << std::endl;
}
void display() const {
if (itemCount == 0) {
std::cout << "Inventory is empty. Add an item!" << std::endl;
return;
}
std::cout << "Inventory:" << std::endl;
for (const auto& item : items) {
std::cout << "- " << item.name << " (" << item.quantity << "), costs $" << item.price << std::endl;
}
}
bool displayItem(std::string itemName) const {
for (const auto& item : items) {
if (itemName == item.name) {
std::cout << "Information of item:" << std::endl;
std::cout << "- Name: " << item.name << std::endl;
std::cout << "- Quantity: " << item.quantity << std::endl;
std::cout << "- Price: " << item.price << std::endl;
return true;
}
}
std::cout << "There was an issue adding your item. Please try again later.";
return false;
}
void search(std::string itemName) const {
for (const auto& item : items) {
if (itemName == item.name) {
displayItem(itemName);
return;
}
}
std::cout << "Could not find the item specified in the system!" << std::endl;
}
// Returns true if there is an existing item with the same name
bool checkItem(std::string itemName) const {
for (const auto& item : items) {
if (item.name == itemName) {
return true;
}
}
return false;
}
bool checkInventory() const {
if (itemCount == 0) {
return false;
}
return true;
}
};
int main() {
Inventory playerInventory;
std::string itemName;
int quantity;
double price;
int console_choice;
code
while (true) {
quantity = 0;
price = 0;
std::cout << "\n--- Inventory Menu ---" << std::endl;
std::cout << "1. Add item" << std::endl;
std::cout << "2. Remove item" << std::endl;
std::cout << "3. Display inventory" << std::endl;
std::cout << "4. Search for item" << std::endl;
std::cout << "5. Exit" << std::endl;
std::cout << "Choose an option: ";
std::cin >> console_choice;
switch (console_choice) {
case 1:
std::cout << "Enter name of item: ";
std::cin >> itemName;
std::cout << "Enter quantity of item: ";
std::cin >> quantity;
if (playerInventory.checkItem(itemName)) {
std::cout << "Enter updated price of item (enter 0 to keep previous price): ";
std::cin >> price;
}
else {
std::cout << "Enter price of item: ";
std::cin >> price;
}
playerInventory.addItem(itemName, quantity, price);
break;
case 2:
std::cout << "Enter item name to remove: ";
std::cin >> itemName;
quantity = 0;
std::cout << "Enter quantity to remove (enter 0 to remove all):";
std::cin >> quantity;
playerInventory.removeItem(itemName, quantity);
break;
case 3:
playerInventory.display();
break;
case 4:
if (!playerInventory.checkInventory()) {
std::cout << "There are no items in inventory!" << std::endl;
break;
}
std::cout << "Enter name of item to search for: ";
std::cin >> itemName;
playerInventory.search(itemName);
break;
case 5:
std::cout << "Exiting inventory system." << std::endl;
return 0;
default:
std::cout << "Invalid option. Please try again." << std::endl;
}
}
return 0;
}
Your C++ inventory management code is well-structured and functional. However, there are several areas where you can enhance readability, efficiency, and adherence to best practices. Below are some suggestions to improve your code, focusing on better coding practices in C++:
Use const Correctly:
Function Parameters: Wherever possible, pass objects as const references to avoid unnecessary copying. For example, instead of void addItem(std::string itemName, int quantity, double itemPrice), use void addItem(const std::string& itemName, int quantity, double itemPrice).
Member Functions: Mark member functions that do not modify the state of the object as const. You have done this in some places (e.g., display()), but ensure consistency across all applicable functions.
Avoid Unnecessary Member Variables:
Redundant itemCount: The itemCount variable mirrors the size of the items vector. Instead of maintaining a separate count, use items.size() when you need the number of items. This reduces redundancy and potential synchronization issues.
cpp
// Remove itemCount entirely and use items.size()
bool checkInventory() const {
return !items.empty();
}
Optimize Destructor Usage:
Destructor Implementation: The ~Inventory() destructor currently calls items.clear(). This is unnecessary because the std::vector destructor automatically handles resource deallocation. Removing the destructor allows the compiler to generate a more efficient one.
cpp
// Remove the destructor
~Inventory() = default;
Encapsulate Class Members:
Private Members: Currently, Item has public member variables. It’s better to keep these private and provide accessor (getter) and mutator (setter) functions. This encapsulation helps maintain control over how data is modified and accessed.
Use size_t Instead of int: For variables representing sizes or indices (like quantity and capacity), use size_t instead of int. This is because size_t is guaranteed to be large enough to represent the size of any object in memory.
cpp
// Example
size_t quantity;
size_t capacity;
Leverage C++11 Range-Based Loops and Algorithms:
Range-Based Loops: You’re already using range-based loops effectively. Ensure consistency across all loops for readability.
Standard Algorithms: Consider using algorithms like std::find_if for searching items, which can make the code more concise and expressive.
cpp
// Example using std::find_if
auto it = std::find_if(items.begin(), items.end(), [&](const Item& item) {
return item.getName() == itemName;
});
if (it != items.end()) {
// Found the item
}
Improve Error Handling and Input Validation:
Validate User Input: Ensure that user inputs are validated to prevent unexpected behavior. For example, check that quantities and prices are non-negative and handle invalid inputs gracefully.
Clear std::cin on Errors: If std::cin encounters an invalid input, clear the error state and ignore the remaining input to prevent infinite loops.
cpp
if (!(std::cin >> quantity)) {
std::cin.clear(); // clear the error flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // discard invalid input
std::cout << "Invalid input for quantity. Please try again." << std::endl;
continue;
}
Use Enumerations for Menu Choices:
Enumerations: Define an enum for menu choices to make the code more readable and maintainable.
Define Constants: Instead of using hard-coded numbers like 10 for the default capacity, define them as constants or use constructor parameters effectively.
Move Constructors and Assignment Operators: For classes that manage resources, implement move constructors and move assignment operators to optimize performance. Although your current classes might not manage resources directly, it's a good practice for scalability.
cpp
class Item {
public:
// Other members...
Item(Item&& other) noexcept
: name(std::move(other.name)),
quantity(other.quantity),
price(other.price) {}
Item& operator=(Item&& other) noexcept {
if (this != &other) {
name = std::move(other.name);
quantity = other.quantity;
price = other.price;
}
return *this;
}
};
Use emplace_back Instead of push_back:
Efficient Insertion: When adding items to the vector, emplace_back can construct the object in place, potentially reducing unnecessary copies.
Naming: Adopt consistent naming conventions for variables and functions to enhance readability. For example, use camelCase or snake_case consistently throughout the code.
cpp
void addItem(const std::string& itemName, int quantity, double itemPrice);
Separate Interface and Implementation:
Header and Source Files: For larger projects, separate class declarations (in header .h files) from implementations (in source .cpp files). This improves code organization and compilation times.
Smart Pointers: Although not directly applicable in your current implementation, if you later manage dynamic memory, prefer smart pointers (std::unique_ptr, std::shared_ptr) over raw pointers to ensure proper resource management and prevent memory leaks.
Enhance removeItem Logic:
Correct Quantity Adjustment: In your removeItem function, when reducing the quantity, ensure you subtract the specified amount rather than setting it directly. Currently, you have it->quantity = quantity;, which likely should be it->quantity -= quantity;.
cpp
it->quantity -= quantity;
Implement Consistent Access Modifiers:
Access Control: Ensure that functions that should not be part of the public interface are marked as private or protected. This encapsulates the behavior and prevents unintended usage.
Leverage std::optional for Search Results:
Optional Return Types: Instead of printing messages within search functions, consider returning an std::optional<Item> to let the caller decide how to handle the absence of an item. This makes your functions more flexible and decoupled from I/O operations.
Namespace Management: Although your current code doesn’t include using namespace std;, it’s good practice to avoid it to prevent name clashes, especially in larger projects or when integrating multiple libraries.
Implement Exception Handling:
Robustness: Enhance your program’s robustness by handling potential exceptions, such as those thrown by invalid memory access or other runtime errors. This ensures that your program can handle unexpected situations gracefully.
Documentation and Comments:
Code Comments: While your code is relatively clear, adding comments and documentation can help others (and your future self) understand the intent and functionality of complex sections.
Docstrings: Consider using documentation generators like Doxygen to create structured documentation for your classes and functions.
Enhance User Experience:
Input Prompts: Make input prompts clearer and more user-friendly. For example, specify acceptable input ranges or formats.
Consistent Messaging: Ensure that all user-facing messages follow a consistent style and provide meaningful feedback.
By incorporating these improvements, your code will adhere more closely to C++ best practices, making it more efficient, maintainable, and scalable. Implementing these suggestions will also enhance your understanding of modern C++ programming paradigms.