我已经尽力想尽一切办法,已经尝试过Chegg和Google,但是我仍然坚持获取文件中生物的数量。我尝试过for和while循环,只应该是两行代码。我什至无法获得更多。
#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
答案 0 :(得分:-2)
这可能应该起作用
Creature creature;
while(!creatureFile.eof())
{
creatureFile.read((char *)&creature, sizeof(creature));
numCreatures++;
}
cout<<"Count is : "<<numCreatures;
循环检查文件结尾。
read()从生物.dat中读取一个生物大小的结构。