Circle.h
#ifndef CIRCLE_H
#define CIRCLE_H
#include <iostream>
#include <fstream>
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);
void SetCircleRadius(double radius) { _circleRadius = radius; }
void SetCircleId(int id) { _circleId = id; }
double GetCircleRadius() const { return _circleRadius; }
int GetCircleId() const { return _circleId; }
private:
double _circleRadius;
int _circleId;
};
#endif
Circle.cpp
#include "Circle.h"
Circle::Circle()
{
_circleId = 0;
_circleRadius = 0.0;
}
Circle::Circle(double radius, int id)
{
_circleId = id;
_circleRadius = radius;
}
Circle::Circle(const Circle& aCircle)
{
_circleId = aCircle._circleId;
_circleRadius = aCircle._circleRadius;
}
ostream& operator <<(ostream& output, const Circle& aCircle)
{
output << "\n ------------" << endl;
output << " Id radius" << endl;
output << " ------------" << endl;
output << " " << aCircle._circleId << " " << aCircle._circleRadius << endl;
output << " ------------" << "\n\n";
return (output);
}
istream& operator >>(istream& input, Circle& aCircle)
{
int quantity;
cout << "\nHow many circles do you want to add ";
input >> quantity;
for (int i = 0; i < quantity; ++i)
{
cout << "\n\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 <conio.h>
#include <fstream>
using namespace std;
#include "Circle.h"
int main ()
{
Circle aCircle;
fstream file;
int option;
do
{
cout << "Menu \n"
<< " (1) Add Circle(s) \n"
<< " (2) Find a Circle by ID \n"
<< " (3) Exit \n"
<< "Your Selection -> ";
cin >> option;
switch (option)
{
case 1:
file.close();
file.clear();
file.open("Circle.dat", ios::out | ios::app | ios::binary);
if (!file)
{
cerr << "\n\nFailed to open file.\n\n";
system("PAUSE");
exit(1);
}
else
{
cin >> aCircle;
file.write(reinterpret_cast<char*> (&aCircle), sizeof(Circle));
}
break;
case 2:
file.close();
file.clear();
cout << "Enter id: ";
int id;
cin >> id;
aCircle.SetCircleId(id);
file.open("Circle.dat", ios::in | ios::app | ios::binary);
if (!file)
{
cerr << "\n\nFailed to open file.\n\n";
system("PAUSE");
exit(1);
}
else
{
file.seekg(id * sizeof(Circle), ios::beg);
file.read(reinterpret_cast<char *> (&aCircle), sizeof(Circle));
cout << aCircle;
}
break;
case 3:
file.close();
cout << "\n\nG o o D B y E\n\n";
exit(0);
break;
default:
cerr << "\nERROR: Wrong Option menu. Please try again.\n\n";
}
} while (option != 3);
return EXIT_SUCCESS;
}
The searching from the file is not working properly ????