如何计算文件中的生物数量?
How do I count number of creatures from a file?
我已经尝试了我能想到的一切,我尝试了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 读取一个生物大小的结构。
相关文章:
- 如何计算文件中的"columns"数?
- C++数据文件、数组和计算赋值
- 如何计算文件中的生物数量?
- 计算二进制文件中的位数
- 通过从文件中读取值来计算移动平均线
- 在目标计算机上访问 POSIX 信号灯时出现可执行文件崩溃(SEGV_MAPERR)
- RPN计算器使用头文件进行计算操作和堆栈;用于堆栈的矢量
- 阅读一个大文件来计算重复K次的单词数
- 在.txt文件上计算重复单词的C 程序
- C :不正确的文件大小计算Winapi
- 将文件从计算机上传到在线服务器上
- C - 读取文件并计算行和列
- 使用循环从加载的 TXT 文件执行计算时出现问题C++
- 如何在两个文本文件中计算不同的数据包编号
- MSVCP100D.dll文件在计算机上丢失了
- c++试图从输入文件中计算总数
- 匹配txt文件并计算字数
- 如何避免在文件末尾计算空行
- 如何使用 boost::文件系统计算目录中的文件数
- c++文件搜索数据库文件并计算下一行