如何计算文件中的生物数量?

How do I count number of creatures from a file?

本文关键字:文件 何计算 计算      更新时间:2023-10-16

我已经尝试了我能想到的一切,我尝试了Chegg和Google,但我仍然坚持在文件中获取生物的数量。我已经尝试过 while 和 for 循环,它只应该是两行代码。我什至无法得到更多。

#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
#include <iomanip>
using namespace std;
// Global variables
const int CREATURE_NAME_SIZE = 30;          // Max length of a creature name
const int CREATURE_TYPE_SIZE = 26;          // Max length of a creature type
const string FILENAME = "creatures.dat";    // Name of file that contains the data
// struct used to create records in file
struct Creature
{
char name[CREATURE_NAME_SIZE];              // Name of the creature
char creatureType[CREATURE_TYPE_SIZE];      // Type of creature
int hp;                                     // Hit points for creature
int armor;                                  // Armor class for creature
int speed;                                  // Speed of creature
};
// This function returns true if the name of the left creature is less than the name of the right creature
// Use this function when running the sort function
bool sortByName(const Creature &lhs, const Creature &rhs)
{
string name1(lhs.name), name2(rhs.name);
return name1 < name2;
}
// Function declarations
// You will need to code the definitions for each of these functions
int getCreatureNumber(int numCreatures);
void displayCreature(fstream& file, int num);
void displaySorted(fstream& file);
int main()
{
char choice;            // choice made by user for menu
fstream creatureFile;   // file stream for input file
int numCreatures;       // the number of creatures saved to the file
// Open the creatureFile for input and binary (one statement of code)
creatureFile.open(FILENAME, ios::out | ios::in | ios::ate | ios::binary);
// Get the number of creatures in the file (two statements of code)
// The number of creatures should be assigned to numCreatures

可能这应该有效

Creature creature;
while(!creatureFile.eof())
{
creatureFile.read((char *)&creature, sizeof(creature));
numCreatures++;
}
cout<<"Count is : "<<numCreatures;

while 循环检查文件末尾。

read(( 从 creatures .dat 读取一个生物大小的结构。