I'm making a program that is supposed to store the circles in a file, each circle should have an id and a radius.
after i Add some circles to the file i need to open it again and search for a specific Id to display it.
Here's what I've done so far. Please any help would be appreciated.
Circle.h
#ifndef CIRCLE_H
#define CIRCLE_H
#include <iostream>
using namespace std;
class Circle
{
friend ostream& operator <<(ostream& output, const Circle& aCircle);
friend istream& operator >>(istream& input, Circle& aCircle);
public:
Circle();
Circle(double radius, int id);
Circle(const Circle& aCircle);
~Circle();
void SetCircleRadius(double radius) { _circleRadius = radius; }
void SetCircleId(int id) { _circleId = id; }
double GetCircleRadius() const { return _circleRadius; }
int GetCircleId() const { return _circleId; }
void FindCirlce()
{
cout << "\nEnter the Id of the circle you want to find ";
cin >> _circleId;
}
private:
double _circleRadius;
int _circleId;
};
#endif
Circle.cpp
#include "Circle.h"
Circle::Circle()
{
_circleId = 12345;
_circleRadius = 0.0;
}
Circle::Circle(double radius, int id)
{
_circleId = id;
_circleRadius = radius;
}
Circle::Circle(const Circle &aCircle)
{
_circleId = aCircle._circleId;
_circleRadius = aCircle._circleRadius;
}
Circle::~Circle()
{
}
ostream& operator <<(ostream& output, const Circle& aCircle)
{
output << "Circle Id: " << aCircle._circleId;
output << "Circle Radius: " << aCircle._circleRadius;
return (output);
}
istream& operator >>(istream& input, Circle& aCircle)
{
int quantity;
cout << "How many circles do you want to add ";
input >> quantity;
for (int i = 0; i < quantity; ++i)
{
cout << "\nEnter the ID of Circle #" << (i + 1) << " : ";
input >> aCircle._circleId;
cout << "Enter Radius of Circle #" << (i + 1) << " : ";
input >> aCircle._circleRadius;
cout << endl;
}
return (input);
}
main.cpp
#include <iostream>
#include <fstream>
using namespace std;
#include "Circle.h"
int main ()
{
Circle aCircle;
fstream file;
int option;
file.open("Circle.txt", ios::in);
if (file.fail())
{
cout << "\n\nError: failed to open file.\n\n";
}
else
{
file.read((char*)& aCircle, sizeof(aCircle));
while (!file.eof())
{
file.read((char*)& aCircle, sizeof(aCircle));
}
file.close();
}
do
{
cout << "Menu \n"
<< " (1) Add Circle(s) \n"
<< " (2) Find a Circle by ID \n"
<< " (3) Exit \n";
cin >> option;
switch (option)
{
case 1:
cin >> aCircle;
break;
case 2:
file.open("Circle.txt", ios::in);
file.read((char*)& aCircle, sizeof(aCircle));
aCircle.FindCirlce();
break;
case 3:
file.clear();
file.open("Circle.txt", ios::out);
if (!file.fail())
{
file.write((char*)& aCircle, sizeof(aCircle));
file.close();
cout << "\n\nGoodbye . . .\n\n";
}
else
cerr << "\n\nERROR: The archive couldn't be opened\n\n";
break;
default:
cerr << "\nERROR: Wrong Option menu.\n\n";
}
} while (option != 3);
return EXIT_SUCCESS;
}