Let's assume your records look like this:
1 Dwarf 2 4
To model this in a class:
class Type_1_Card
{
int type;
std::string name;
int attack;
int health;
};
In modeling, you choose a type and member that best fits the column of data.
Each row will be an instance of the model.
Speaking of rows, you'll need some kind of container for each row (otherwise known as a database). Since the number of rows is unknown at run-time, use a std::vector
, because it can expand as necessary.
std::vector<Type_1_Card> database;
To honor the principles of data hiding and encapsulation, we'll have the class input the data, since the class knows the layout (fields and members). C++ allows overloading of operators and methods, so we'll overload a familiar method: operator>>
.
class Type_1_Card
{
// yada, yada, yada
public:
friend std::istream& operator>>(std::istream& input, Type_1_Card& card);
};
std::istream&
Type_1_Card ::
operator>>(std::istream& input, Type_1_Card& card)
{
input >> card.type;
input >> card.name;
input >> card.attack;
input >> card.health;
return input;
}
This hides the data by allowing the following code to read in the cards:
std::fstream data_file(/*...*/);
Type_1_Card card;
while (data_file >> card)
{
database.push_back(card);
}
Magically, the contents of the card
are not exposed, hidden, and the functionality is encapsulated into the class or object.
Edit 1: Expanding the encapsulation
In your program, you may want to find a card by name. You can add a method to the class, then search the database:
class Type_1_Card
{
// yada, yada, yada
public:
bool is_card_name(const std::string& key_name) const
{
// Remember, comparison is case sensitive, 'A' != 'a'
return name == key_name;
}
};
This allows you to search the database for a card using a name.
Here's the brute force technique. There are simpler methods that use library functions, but that is left for further research.
const size_t index = 0U;
const size_t size = database.size();
for (index = 0; index < size; ++index)
{
if (database[index].is_card_name("Dwarf"))
{
std::cout << "Dwarf card found at index " << index << "\n";
}
}