File I/O
Reading and Writing from/to a file
main.cpp
// Project 09-02
// Name:DynamicFileRectangle
#include <iostream>
#include <vector>
#include <fstream>
#include "Rectangle.h"
using namespace std;
void populateVector(vector<Rectangle*> &rec, ifstream& inputFile);
void outputToFile(vector<Rectangle*> &rectangles, ofstream& outputFile);
void clearVector(vector<Rectangle*> &rectangles);
int main()
{
cout << "Opening rectangles.txt";
ifstream inputFile;
ofstream outputFile;
inputFile.open("rectangles.txt");
outputFile.open("output.txt");
if (!inputFile) {
cerr << "Error opening file, grabbing parachute and jumping out";
return 1;
}
cout << "Processing data..." << endl;
vector<Rectangle*> Rectangles;
populateVector(Rectangles, inputFile);
outputToFile(Rectangles, outputFile);
clearVector(Rectangles);
cout << "Done!" << endl;
inputFile.close();
outputFile.close();
return 0;
}
void populateVector(vector<Rectangle*> &rec, ifstream& inputFile)
{
Rectangle* temp;
int length;
int width;
while (!inputFile.eof()) {
inputFile >> length >> width;
temp = new Rectangle (length, width);
rec.push_back(temp);
}
}
void outputToFile(vector<Rectangle*> &rectangles, ofstream& outputFile)
{
for (Rectangle* rectangle : rectangles) {
outputFile << "Area: " << rectangle->area() << " " << '\t' << rectangle->perimeter() << endl;
}
}
void clearVector(vector<Rectangle *>& rectangles)
{
for (Rectangle *rectangle : rectangles) {
delete rectangle;
rectangle = nullptr; // not required since rectangles.clear() will be called
}
rectangles.clear();
}
Rectangle.h
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle
{
public:
Rectangle();
Rectangle(double length, double width);
double getLength() const;
double getWidth() const;
void setLength(double length);
void setWidth(double width);
double area() const;
double perimeter() const;
private:
double length;
double width;
};
#endif
Rectangle.cpp
#include "Rectangle.h"
Rectangle::Rectangle()
{
this->length = 1.0;
this->width = 1.0;
}
Rectangle::Rectangle(double length, double width)
{
this->length = length;
this->width = width;
}
double Rectangle::getLength() const
{
return length;
}
double Rectangle::getWidth() const
{
return width;
}
void Rectangle::setLength(double length)
{
this->length = length;
}
void Rectangle::setWidth(double width)
{
this->width = width;
}
double Rectangle::area() const
{
return length * width;
}
double Rectangle::perimeter() const
{
return 2 * length + 2 * width;
}