Calling void function problems - c++

Hello I have problems calling the void initialize() function in my code. I am supposed to get an array that looks like this
//cccccccccccccccccccccccccc
cxxxxxxxxxxxxxxxxxxxxxxxxc
cxxxxxxxxxxxxxxxxxxxxxxxxc
cxxxxxxxxxxxxxxxxxxxxxxxxc
cxxxxxxxxxxxxxxxxxxxxxxxxc
cxxxxhhhhhhhxxxxxxxxxxxxxc
cxxxxhhhhhhhxxxxxxxxxxxxxc
cxxxxhhhhhhhxxxxxxxxxxxxxc
cxxxxhhhhhhhxxxxxxxxxxxxxc
cxxxxxxxxxxxxxxxxxxxxxxxxc
cccccccccccccccccccccccccc//
where the array is defined in Initialize() and the variables come from FIN , SteamPipe and GridPT classes. My code is giving me the first set of answers before the array but when it gets to the array I only get the symbol '?' that is what it's been designated in the class GridPT.
I think that the way I am calling the void function is wrong or there is something wrong passing the variables? I already tried taking out the const but still the same.
here is my code .h file
#include<iostream>
#include<istream>
#include<cmath>
#include<cstdlib>
using namespace std;
const int maxFinHeight = 100;
const int maxFinWidth = 100;
class Steampipe
{
private:
int height, width;
double steamTemp;
public:
Steampipe (int H = 0, int W = 0, double sT = 0.0)
{
height = H;
width = W;
steamTemp = sT;
}
// Access function definitions
int getWidth()const{return width;};
int getHeight()const{return height;};
double getSteamTemp()const{return steamTemp;};
void setWidth(int dummysteamwidth) {width = dummysteamwidth;};
void setHeight(int dummysteamheight){height = dummysteamheight;};
void setSteamTemp(double dummysteamtemp){steamTemp = dummysteamtemp;};
// Access function definitions
friend istream& operator>>(istream& , Steampipe& ); // YOU MUST DEFINE
friend ostream& operator<<(ostream& , const Steampipe& ); // YOU MUST DEFINE
};
class GridPt
{
private:
double temperature;
char symbol;
public:
GridPt(double t = 0.0, char s = '?')
{
temperature = t;
symbol = s;
}
// Access function definitions
double getTemperature()const {return temperature;};
char getsymbol() const {return symbol;};
void setTemperature (double T=0) {T=temperature;}
void setsymbol (char S='?'){S=symbol;}
};
class Fin
{
private:
int width, height; //width and height of fin
int pipeLocationX, pipeLocationY; //grid location of lower left corner of steampipe
double boundaryTemp; //temperature of fin surroundings
Steampipe Pipe; //steampipe object - COMPOSITION
GridPt GridArray[maxFinHeight][maxFinWidth]; // array of GridPts - COMPOSITION
public:
int getwidth() {return width;}
int getheight() {return height;}
int getpipeLocationX(){return pipeLocationX;}
int getpipeLocationY(){return pipeLocationX;}
double get_boundarytemp(){return boundaryTemp;}
void setwidth (int w){w=width;}
void setheight (int h){h=height;}
friend istream& operator>>(istream& , Fin& ); // YOU MUST DEFINE
friend ostream& operator<<(ostream& , const Fin& ); // YOU MUST DEFINE
void initialize(); // YOU MUST DEFINE
};
void Fin::initialize()
{
int j(0) ,i(0);
for ( i = 0; i < height; i++)
{
for ( j = 0; j < width; j++)
{
if ( j == pipeLocationX && i == pipeLocationY
&& i < Pipe.getHeight() + pipeLocationY
&& j < Pipe.getWidth() + pipeLocationX)
{
GridArray [j][i].setTemperature(Pipe.getSteamTemp());
GridArray [j][i].setsymbol('H');
}
else if (j == (width -1) || i == (height -1) || j == 0 || i == 0)
{
GridArray [j][i].setTemperature(boundaryTemp);
GridArray [j][i].setsymbol('C');
}
else
{
GridArray [j][i].setTemperature((Pipe.getSteamTemp() + boundaryTemp)/2);
GridArray [j][i].setsymbol('X');
}
}
}
}
istream &operator >> (istream & in, Fin& f)
{
int ws, hs;
double ts;
char comma;
cout << "Enter the height of the fin (integer) >>> ";
in >> f.height;
cout << "Enter the width of the fin (integer) >>> " ;
in >> f.width;
cout << "Enter the height of the streampipe (integer) >>> ";
in >>hs;
f.Pipe.setHeight(hs);
cout << "Enter the width of the steampipe (integer) >>> ";
in >> ws;
f.Pipe.setWidth(ws);
cout << "Enter coordinates of lower left corner of steampipe (X,Y) >>> ";
in >> f.pipeLocationX >> comma >> f.pipeLocationY;
cout << "Enter the steam temperature (floating point) >>> ";
in >> ts;
f.Pipe.setSteamTemp(ts);
cout << "Enter the temperature around the fin (floating point) >>> ";
in >> f.boundaryTemp;
return in;
}
ostream &operator << (ostream &stream, const Fin& t)
{
int i = 0;
int j = 0;
stream << "The width of the fin is " << t.width << endl;
stream << "The height of the fin is " << t.height << endl;
stream << "The outside temperature is " << t.boundaryTemp << endl;
stream << "The lower left corner of the steam pipe is at "
<< t.pipeLocationX << "," << t.pipeLocationY << endl;
stream << "The steampipe width is " << t.Pipe.getWidth() << endl;
stream << "the steampipe height is " << t.Pipe.getHeight() << endl;
stream << "The temperature of the steam is " << t.Pipe.getSteamTemp() << endl;
for ( i = 0; i < t.height; i++)
{
for ( j = 0; j < t.width; j++)
{
if (j == t.pipeLocationX && i == t.pipeLocationY && i < t.Pipe.getHeight() + t.pipeLocationY && j < t.Pipe.getWidth() + t.pipeLocationX)
{
t.GridArray [j][i].getTemperature();
stream<<t.GridArray [j][i].getsymbol();
}
else if (j == (t.width -1) || i == (t.height -1) || j == 0 || i == 0)
{
t.GridArray [j][i].getTemperature();
stream<<t.GridArray [j][i].getsymbol();
}
else
{
t.GridArray [j][i].getTemperature();
stream<<t.GridArray [j][i].getsymbol();
}
}stream<<endl;
}
int coorx(0),coory(0);char comma;
stream << "Enter the coordinates of the gridpoint of interest (X,Y) >>> "
<< endl;
cin>>coorx>>comma>>coory;
stream<<"The temperature at location ("<<coorx<<","<<coory<<") is "
<< t.GridArray << endl;
return stream;
}
and my driver file cpp is:
#include "pipe.h"
int main()
{
Fin one;
cin >> one;
one.initialize();
cout << one;
return 0;
}
Any suggestions will be very appreciated. Thank you

In your code the following is wrong:
void setTemperature (double T=0) {T=temperature;}
void setsymbol (char S='?'){S=symbol;}
It must be:
void setTemperature (double T=0) {temperature = T;}
void setsymbol (char S='?') { symbol = S;}
As an aside: It is not a good habit to place function definitions in your header (unless it's a template), rather put them in a source-file with just the declarations in the header.
In your code you also use t.GridArray in your output-stream directly:
stream<<t.GridArray;
This will not work.
It is not a function, or a type that the ostream will understand.
Use the i and j variables you have declared and step through each element of the array to print them, same as when you initialize the array.

Related

Having trouble moving class to seperate .cpp and .h file.

I created a basic consol program that creates a box of the users desired height and width. I wanted to learn how classes worked so I just used one file. Now i'm trying to properly put the class into a .h and .cpp file. Can someone point out what I'm doing wrong and how I should fix it?
Original Code with just a main.cpp:
#include "stdafx.h"
#include <iostream>
using namespace std;
class BoxClass {
//prv variables
unsigned short int width;
int height, i;
float space_Value;
float height_Count = 1;
bool error = false;
//prv functions
void Print_Rectangle(int x, int y) {
//calc
space_Value = (3 * x) - 4;
//draw top of box
for (width = 1; width < x; width += 1) {
cout << "...";
}
cout << "\n";
//draw sides
for (height = 1; height < y; height += 1) {
cout << ":";
height_Count++;
for (width = 1; width < space_Value; width += 1) {
cout << " ";
}
cout << ":\n";
}
//draw bottom
cout << ":";
for (width = 1; width < space_Value; width += 1) {
cout << ".";
}
cout << ":\n";
}
public:
//function shows area of individual spaces
float Rectangle_Area() {
if (error == false) {
return (height_Count - .5)*(space_Value - 1);
}
else {
return 0;
}
}
//function shows area of individual spaces
// constructor
BoxClass(int x, int y, int amount) {
if (x <= 41) {
for (i = 1; i <= amount; i += 1) {
Print_Rectangle(x, y);
}
}
else {
error = true;
cout << "Error - width must be below 42!\n";
}
};
};
int main() {
//variable declaration/definition
int width_Var;
int height_Var;
int number_of_Boxes;
//object declaration/Body
cout << "Enter width of rectangle/box\nWidth = ";
cin >> width_Var;
cout << "Enter height of rectangle/box\nHeight = ";
cin >> height_Var;
cout << "How many rectangles/boxes do you want?\n";
cin >> number_of_Boxes;
BoxClass box1(width_Var, height_Var, number_of_Boxes);
cout <<"Box Area = "<<box1.Rectangle_Area() << endl;
//exit
cout << "\n\n\n\n\n";
system("pause");
return 0;
}
New Code with main.cpp, BoxClass.h, Boxclass.cpp:
main.cpp:
#include "BoxClass.h"
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
//variable declaration/definition
int width_Var;
int height_Var;
int number_of_Boxes;
//object declaration/Body
cout << "Enter width of rectangle/box\nWidth = ";
cin >> width_Var;
cout << "Enter height of rectangle/box\nHeight = ";
cin >> height_Var;
cout << "How many rectangles/boxes do you want?\n";
cin >> number_of_Boxes;
BoxClass box1(width_Var, height_Var, number_of_Boxes);
cout <<"Box Area = "<<box1.Rectangle_Area() << endl;
//exit
cout << "\n\n\n\n\n";
system("pause");
return 0;
}
BoxClass.h:
#ifndef BOXCLASS_H
#define BOXCLASS_H
class BoxClass {
//prv variables
unsigned short int width;
int height, i;
float space_Value;
float height_Count = 1;
bool error = false;
//prv functions
void Print_Rectangle(int x, int y);
public:
//function shows area of individual spaces
float Rectangle_Area();
//function shows area of individual spaces
// constructor
BoxClass(int x, int y, int amount);
};
#endif
BoxClass.cpp:
#include "BoxClass.h"
#include "stdafx.h"
#include <iostream>
using namespace std;
BoxClass::Print_Rectangle(int x, int y) {
//calc
space_Value = (3 * x) - 4;
//draw top of box
for (width = 1; width < x; width += 1) {
cout << "...";
}
cout << "\n";
//draw sides
for (height = 1; height < y; height += 1) {
cout << ":";
height_Count++;
for (width = 1; width < space_Value; width += 1) {
cout << " ";
}
cout << ":\n";
}
//draw bottom
cout << ":";
for (width = 1; width < space_Value; width += 1) {
cout << ".";
}
cout << ":\n";
}
//function shows area of individual spaces
BoxClass::Rectangle_Area() {
if (error == false) {
return (height_Count - .5)*(space_Value - 1);
}
else {
return 0;
}
}
// constructor
BoxClass::BoxClass(int x, int y, int amount) {
if (x <= 41) {
for (i = 1; i <= amount; i += 1) {
Print_Rectangle(x, y);
}
}
else {
error = true;
cout << "Error - width must be below 42!\n";
}
};
You forgot about type specifier so you should change this in your BoxClass.cpp:
BoxClass::Print_Rectangle(int x, int y)
...
BoxClass::Rectangle_Area()
to this:
void BoxClass::Print_Rectangle(int x, int y)
...
float BoxClass::Rectangle_Area()
Also a bit aside of topic, thing that I can suggest you for future is to use #pragma once instead include guards.
You need a constructor, which is where you'll set the values of height_Count and error. You should probably also define a destructor, even though at this point there is probably nothing to do there. It's just a good idea. According to Scott Meyers in Effective C++, you should also define a copy constructor and a copy assignment operator.
This is in addition to the type-specifier suggestion already posted.

C++ Console is blank when program is run

This might be a stupid question I'm still very new to coding. For my CS class I was given code for the basics of a boardgame. When I try to run the code it just comes up blank in my console, I tried to print "check" at the very beginning of main but still nothing prints to the console. No errors come up
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
class square {
private:
int move;
string message;
char symbol;
public:
square();
void print();
int action();
void set(int, char, string);
};
void print_board(square[], int, int);
void read_board(square[]);
void check_position(int &);
const int board_length = 20;
int main() {
cout << "check";
int current_player = 1, roll;
int player1_position = 0, player2_position = 0;
square the_board[board_length];
srand(time(NULL));
read_board(the_board);
print_board(the_board, player1_position, 1);
print_board(the_board, player2_position, 2);
do {
cout << "\n\n\nPlayer " << current_player << " type enter to roll.\n";
cin.ignore();
roll = 1 + (rand() % 5);
cout << "Player " << current_player << " rolled a " << roll << ".\n";
if (current_player == 1) {
player1_position += roll;
check_position(player1_position);
player1_position += the_board[player1_position].action();
check_position(player1_position);
} else {
player2_position += roll;
check_position(player2_position);
player2_position += the_board[player2_position].action();
check_position(player2_position);
}
print_board(the_board, player1_position, 1);
print_board(the_board, player2_position, 2);
current_player = (current_player % 2) + 1;
} while ((player1_position < board_length-1) && (player2_position < board_length - 1));
current_player = (current_player % 2) + 1;
cout << "\nPlayer " << current_player << " Wins!!!\n";
cin.ignore();
return 0;
}
void read_board(square b[]) {
ifstream infile;
infile.open("game.txt");
int square_number, square_move;
string square_message;
char square_symbol;
while (!infile.eof()) {
infile >> square_number >> square_move >> square_symbol;
getline(infile, square_message);
if (square_number < board_length) {
b[square_number].set(square_move, square_symbol, square_message);
}
}
}
void print_board(square b[], int player_position, int player_number) {
for (int i=0; i < board_length; i++) {
if (i != player_position) {
b[i].print();
} else {
cout << player_number;
}
}
cout << "Goal\n";
for (int i=0; i < board_length; i++) {
cout << "-";
}
cout << "\n";
}
void check_position(int &p) {
if (p < 0) {
p = 0;
}
if (p >= board_length) {
p = board_length - 1;
}
}
square::square() {
symbol = ' ';
move = 0;
message = "";
}
int square::action() {
cout << message << endl;
return move;
}
void square::print() {
cout << symbol;
}
void square::set (int m, char s, string a_message) {
move = m;
symbol = s;
message = a_message;
}
Modify you read_board() to
void read_board(square b[]) {
ifstream infile;
infile.open("game.txt");
int square_number, square_move;
string square_message;
char square_symbol;
while (infile >> square_number >> square_move >> square_symbol) {
getline(infile, square_message);
if (square_number < board_length) {
b[square_number].set(square_move, square_symbol, quare_message);
}
}
}
Change cout<<"check"; to cout<<"check"<<endl;
Without the new line added, the out buffer is not flushed before your code gets hung in your read_board function

Function to check dimension value and what it is

I am trying to write a program that checks to see if a dimension of a rectangle is greater than zero. In the void function Check i tried using an array to check the value and used a string to display what dimension was wrong to the user. I am getting an error that it "cannot convert argument 1 from 'double[6]' to 'double'.
#include <iostream>
#include <string>
using namespace std;
void Check(double, string);
int main()
{
const int size = 3;
double DimArray[size];
string MyArray[size] = { "Height", "Length", "Width"};
cout << "Enter the height, length and width of rectangle: ";
cin >> DimArray[0] >> DimArray[1] >> DimArray[2];
Check(DimArray, MyArray);
return 0;
}
void Check(double arr1[], string arr2[])
{
int i;
for (i = 0; i < 4; i++)
{
if (arr1[i] <= 0)
cout << "Your entered " << arr2[i] << "is less than zero!";
cout << "Please enter a valid number --> ";
cin >> arr1[i];
}
}
You should declare the function correctly. Instead of
void Check(double, string);
there should be
void Check( double[], const std::string[], size_t );
Also instead of the loop in the function body
for (i = 0; i < 4; i++)
there must be
for (i = 0; i < 3; i++)
And the function could be defined as
void Check( double arr1[], const std::string arr2[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
while ( arr1[i] <= 0 )
{
std::cout << "Your entered " << arr2[i] << "is not positive!\n";
std::cout << "Please enter a valid number --> ";
std::cin >> arr1[i];
}
}
}
Or if you will define file-wide constant
const size_t SIZE = 3;
then the function definition (and correspondingly its declaration) could be simplified
void Check( double arr1[], const std::string arr2[] )
{
for ( size_t i = 0; i < SIZE; i++ )
{
while ( arr1[i] <= 0 )
{
std::cout << "Your entered " << arr2[i] << "is not positive!\n";
std::cout << "Please enter a valid number --> ";
std::cin >> arr1[i];
}
}
}
Also instead of the array of std::string(s) it would be better to define an array of const char *
const char * MyArray[size] = { "Height", "Length", "Width"};
because as I have understood you are not going to change it.
Since your prototype expects a type double and you are passing a double arr1[]..
Change the prototype:
void Check(double, string);
to:
void Check(double arr1[], string arr2[])

An error I don't understand [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 8 years ago.
I'm getting this error when I compile, but I'm not sure how to fix it. I see that it has something to do with trying to use ofstream outFile; to write to a file. I've diddled with it, but I'm not sure what the problem is.
1>Rectangle.obj : error LNK2001: unresolved external symbol "class std::basic_ofstream<char,struct std::char_traits<char> > outFile" (?outFile##3V?$basic_ofstream#DU?$char_traits#D#std###std##A)
1>E:\Hw11_overload_Hw8\Debug\Rectangle.exe : fatal error LNK1120: 1 unresolved externals
This is my header file.
#ifndef Rectangle_h
#define Rectangle_h
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
class Rectangle
{
friend istream &operator>> (istream &input, Rectangle &grid);
friend ostream &operator<< (ostream &output, Rectangle grid);
private:
int i, j, h, x1, x2, y1, y2, perimeter, area, width, height;
char inner, outer;
string name;
public:
Rectangle();
void printGrid();
void setX1(int x11);
int getX1();
void setX2(int x21);
int getX2();
void setY1(int y11);
int getY1();
void setY2(int y21);
int getY2();
void setInner(char inner1);
char getInner();
void setOuter(char outer1);
char getOuter();
void findPerimeter();
void findArea();
void findWidth();
void findHeight();
void setName(string name1);
string getName();
int Menu();
};
#endif
And here is my source file.
#include "Rectangle.h"
extern ofstream outFile;
Rectangle::Rectangle()
{
x1 = 0;
x2 = 1;
y1 = 0;
y2 = 1;
}
void Rectangle::setX1(int x11)
{
x1 = x11;
}
int Rectangle::getX1()
{
return x1;
}
void Rectangle::setX2(int x21)
{
x2 = x21;
}
int Rectangle::getX2()
{
return x2;
}
void Rectangle::setY1(int y11)
{
y1 = y11;
}
int Rectangle::getY1()
{
return y1;
}
void Rectangle::setY2(int y21)
{
y2 = y21;
}
int Rectangle::getY2()
{
return y2;
}
void Rectangle::findPerimeter()
{
perimeter = ((x2 - x1) + (y2 - y1)) * 2;
cout << "The perimeter of the rectangle is: " << perimeter << endl;
}
void Rectangle::findArea()
{
area = (x2 - x1) * (y2 - y1);
cout << "The area of the rectangle is: " << area << endl;
}
void Rectangle::findWidth()
{
width = x2 - x1;
cout << "The width of the rectangle is: " << width << endl;
}
void Rectangle::findHeight()
{
height = y2 - y1;
cout << "The height of the rectangle is: " << height << endl;
}
void Rectangle::setInner(char inner1)
{
inner = inner1;
}
char Rectangle::getInner()
{
return inner;
}
void Rectangle::setOuter(char outer1)
{
outer = outer1;
}
char Rectangle::getOuter()
{
return outer;
}
void Rectangle::setName(string name1)
{
name = name1;
}
string Rectangle::getName()
{
return name;
}
void Rectangle::printGrid()
{
int numrows = 25;
int numcols = 25;
int current_row = numrows; // starting row number
int current_col = 1; // starting col number
char output = '.';
for(i = 0; i < numrows; i++) // prints 25 rows of 25 dots
{
cout << current_row << '\t'; // Print out current row number
outFile << current_row << '\t';
//This is out loop for each ROW
//Print out dots in each row OR stuff for the rectangle
for(j = 1; j <= numcols; j++) {
output = '.'; // Initialize output with our default value of "."
if ((current_col >= x1) && (current_col <= x2) && (current_row >= y1) && (current_row <= y2)) {
output = outer;
}
if ((current_col > x1) && (current_col < x2) && (current_row > y1) && (current_row < y2)) {
output = inner;
}
cout << output << " "; // output our "output" value and a space
outFile << output << " ";
current_col++; //Increment current column, because this is the end of this column loop iteration
} // Close column loop
cout << endl; //...and a new line
outFile << endl;
current_col = 1; // reset column count for next iteration
current_row--; // decrement current row number
} // Close Row loop
//output column labels across bottom line
cout << '\t';
outFile << '\t';
// put 1 -> 25 across the bottom
for (i = 1; i <= 25; i++)
{
if(i < 10)
{
cout << i << " ";
outFile << i << " ";
}
if(i > 9)
{
cout << i << " ";
outFile << i << " ";
}
}
// Spit out a couple of blank lines
cout << endl << endl;
outFile << endl << endl;
}
int Rectangle::Menu()
{
ifstream inFile;
int choice;
cout << "1. Enter information about a rectangle. " << endl;
cout << "2. Search for a rectangle. " << endl;
cout << "3. Print the perimeter and the area of the rectangle. " << endl;
cout << "4. Print the width and height of the rectangle. " << endl;
cout << "5. Draw a particular rectangle. " << endl;
cout << "6. Quit. " << endl;
cout << "Enter your choice. " << endl;
inFile >> choice;
cout << endl << endl;
return choice;
}
istream &operator>> (istream &input, Rectangle &grid)
{
ifstream inFile;
ofstream outFile;
Rectangle rect[10];
int x11, x21, y11, y21, choice, numRectangles = 0, i = 0;
char inner1, outer1;
string name1;
inFile.open ("rectangle.in");
outFile.open ("rectangle.out");
if (!inFile)
{
cout << "ERROR: inFile does not exist. " << endl;
system("pause");
}
if (!outFile)
{
cout << "ERROR: outFile does not exist. " << endl;
system("pause");
}
choice = rect[i].Menu();
while(choice >= 1 && choice <= 6)
{
if(choice == 1)
{ do
{
cout << "Enter x1, x2, y1, and y2 such that x1 < x2 and y1 < y2: " << endl;
inFile >> x11;
inFile >> x21;
inFile >> y11;
inFile >> y21;
cout << "Enter a character for the interior of the rectangle. \n";
inFile >> inner1;
cout << "Enter a character for the exterior of the rectangle. \n";
inFile >> outer1;
cout << "Enter a name for the rectangle. \n";
inFile >> name1;
rect[numRectangles].setX1(x11);
rect[numRectangles].setX2(x21);
rect[numRectangles].setY1(y11);
rect[numRectangles].setY2(y21);
rect[numRectangles].setInner(inner1);
rect[numRectangles].setOuter(outer1);
rect[numRectangles].setName(name1);
numRectangles++;
}
while(x11 >= x21 || y11 >= y21);
cout << endl << "Rectangle accepted. \n" << endl;
}
if (choice == 2)
{
cout << "To search for a rectangle, enter the name of the rectangle. " << endl;
cin >> name1;
for(i = 0; i < numRectangles; i++)
{
if(name1 == rect[i].getName())
{
rect[i].findPerimeter();
rect[i].findArea();
rect[i].findWidth();
rect[i].findHeight();
rect[i].printGrid();
system("pause");
}
}
if(name1 != rect[i].getName())
{
cout << "ERROR! Rectangle doesn't exist!" << endl << endl;
system("pause");
}
}
if(choice == 3)
{
for(i = 0; i < numRectangles; i++)
{
rect[i].findPerimeter();
cout << endl;
rect[i].findArea();
cout << endl;
}
}
if(choice == 4)
{
for(i = 0; i < numRectangles; i++)
{
rect[i].findWidth();
cout << endl;
rect[i].findHeight();
cout << endl;
}
}
if(choice == 5)
{
for(i = 0; i < numRectangles; i++)
{
rect[i].printGrid();
cout << endl;
}
}
if(choice == 6)
{
cout << "Bye bye!" << endl;
system("pause");
}
choice = rect[i].Menu();
return input;
} // End of while loop
inFile.close();
outFile.close();
}
ostream &operator<< (ostream &output, Rectangle grid)
{
return output;
}
And here is my main function
#include "Rectangle.h"
int main()
Rectangle rect[10];
int numRectangles;
for(int i = 0; i < numRectangles; i++)
{
cin >> rect[i];
cout << rect[i];
}
}
Problems:
You have declared that outFile will have external linkage. std::ofstream has no default constructor.
std::ofstream has a non-default constructor and takes two parameters.. The first is the location of the file and the second (which is default btw) is how you plan to open/write it.
Thus you can fix this error by replacing extern ofstream outFile; with:
ofstream outFile("output.txt"); within Rectangle.cpp
There is no need to declare it as extern within the .cpp file as far as I am aware.
Next, istream& operator>> (istream& input, Rectangle& grid) is returning NOTHING..
It should be returning input before the function finishes.
Finally, you are missing a curly bracket after main's () brackets.
You main.cpp should look like:
#include "Rectangle.h"
int main()
{
Rectangle rect[10];
int numRectangles;
for(int i = 0; i < numRectangles; i++)
{
cin >> rect[i];
cout << rect[i];
}
}
Would it really kill you to follow convention and format your code?
If done correctly, your code would look like:
Rectangle.h:
#ifndef Rectangle_h
#define Rectangle_h
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
class Rectangle
{
private:
friend istream& operator>> (istream& input, Rectangle& grid);
friend ostream& operator<< (ostream& output, Rectangle grid);
int i, j, h, x1, x2, y1, y2, perimeter, area, width, height;
char inner, outer;
string name;
public:
Rectangle();
void printGrid();
void setX1(int x11);
int getX1();
void setX2(int x21);
int getX2();
void setY1(int y11);
int getY1();
void setY2(int y21);
int getY2();
void setInner(char inner1);
char getInner();
void setOuter(char outer1);
char getOuter();
void findPerimeter();
void findArea();
void findWidth();
void findHeight();
void setName(string name1);
string getName();
int Menu();
};
#endif
Rectangle.cpp:
#include "Rectangle.h"
ofstream outFile("output.txt");
Rectangle::Rectangle()
{
x1 = 0;
x2 = 1;
y1 = 0;
y2 = 1;
}
void Rectangle::setX1(int x11)
{
x1 = x11;
}
int Rectangle::getX1()
{
return x1;
}
void Rectangle::setX2(int x21)
{
x2 = x21;
}
int Rectangle::getX2()
{
return x2;
}
void Rectangle::setY1(int y11)
{
y1 = y11;
}
int Rectangle::getY1()
{
return y1;
}
void Rectangle::setY2(int y21)
{
y2 = y21;
}
int Rectangle::getY2()
{
return y2;
}
void Rectangle::findPerimeter()
{
perimeter = ((x2 - x1) + (y2 - y1)) * 2;
cout << "The perimeter of the rectangle is: " << perimeter << endl;
}
void Rectangle::findArea()
{
area = (x2 - x1) * (y2 - y1);
cout << "The area of the rectangle is: " << area << endl;
}
void Rectangle::findWidth()
{
width = x2 - x1;
cout << "The width of the rectangle is: " << width << endl;
}
void Rectangle::findHeight()
{
height = y2 - y1;
cout << "The height of the rectangle is: " << height << endl;
}
void Rectangle::setInner(char inner1)
{
inner = inner1;
}
char Rectangle::getInner()
{
return inner;
}
void Rectangle::setOuter(char outer1)
{
outer = outer1;
}
char Rectangle::getOuter()
{
return outer;
}
void Rectangle::setName(string name1)
{
name = name1;
}
string Rectangle::getName()
{
return name;
}
void Rectangle::printGrid()
{
int numrows = 25;
int numcols = 25;
int current_row = numrows; // starting row number
int current_col = 1; // starting col number
char output = '.';
for(i = 0; i < numrows; i++) // prints 25 rows of 25 dots
{
cout << current_row << '\t'; // Print out current row number
outFile << current_row << '\t';
//This is out loop for each ROW
//Print out dots in each row OR stuff for the rectangle
for(j = 1; j <= numcols; j++)
{
output = '.'; // Initialize output with our default value of "."
if ((current_col >= x1) && (current_col <= x2) && (current_row >= y1) && (current_row <= y2))
{
output = outer;
}
if ((current_col > x1) && (current_col < x2) && (current_row > y1) && (current_row < y2))
{
output = inner;
}
cout << output << " "; // output our "output" value and a space
outFile << output << " ";
current_col++; //Increment current column, because this is the end of this column loop iteration
} // Close column loop
cout << endl; //...and a new line
outFile << endl;
current_col = 1; // reset column count for next iteration
current_row--; // decrement current row number
} // Close Row loop
//output column labels across bottom line
cout << '\t';
outFile << '\t';
// put 1 -> 25 across the bottom
for (i = 1; i <= 25; i++)
{
if(i < 10)
{
cout << i << " ";
outFile << i << " ";
}
if(i > 9)
{
cout << i << " ";
outFile << i << " ";
}
}
// Spit out a couple of blank lines
cout << endl << endl;
outFile << endl << endl;
}
int Rectangle::Menu()
{
ifstream inFile;
int choice;
cout << "1. Enter information about a rectangle. " << endl;
cout << "2. Search for a rectangle. " << endl;
cout << "3. Print the perimeter and the area of the rectangle. " << endl;
cout << "4. Print the width and height of the rectangle. " << endl;
cout << "5. Draw a particular rectangle. " << endl;
cout << "6. Quit. " << endl;
cout << "Enter your choice. " << endl;
inFile >> choice;
cout << endl << endl;
return choice;
}
istream& operator>> (istream& input, Rectangle& grid)
{
ifstream inFile;
ofstream outFile;
Rectangle rect[10];
int x11, x21, y11, y21, choice, numRectangles = 0, i = 0;
char inner1, outer1;
string name1;
inFile.open ("rectangle.in");
outFile.open ("rectangle.out");
if (!inFile)
{
cout << "ERROR: inFile does not exist. " << endl;
system("pause");
}
if (!outFile)
{
cout << "ERROR: outFile does not exist. " << endl;
system("pause");
}
choice = rect[i].Menu();
while(choice >= 1 && choice <= 6)
{
if(choice == 1)
{
do
{
cout << "Enter x1, x2, y1, and y2 such that x1 < x2 and y1 < y2: " << endl;
inFile >> x11;
inFile >> x21;
inFile >> y11;
inFile >> y21;
cout << "Enter a character for the interior of the rectangle. \n";
inFile >> inner1;
cout << "Enter a character for the exterior of the rectangle. \n";
inFile >> outer1;
cout << "Enter a name for the rectangle. \n";
inFile >> name1;
rect[numRectangles].setX1(x11);
rect[numRectangles].setX2(x21);
rect[numRectangles].setY1(y11);
rect[numRectangles].setY2(y21);
rect[numRectangles].setInner(inner1);
rect[numRectangles].setOuter(outer1);
rect[numRectangles].setName(name1);
numRectangles++;
}
while(x11 >= x21 || y11 >= y21);
cout << endl << "Rectangle accepted. \n" << endl;
}
if (choice == 2)
{
cout << "To search for a rectangle, enter the name of the rectangle. " << endl;
cin >> name1;
for(i = 0; i < numRectangles; i++)
{
if(name1 == rect[i].getName())
{
rect[i].findPerimeter();
rect[i].findArea();
rect[i].findWidth();
rect[i].findHeight();
rect[i].printGrid();
system("pause");
}
}
if(name1 != rect[i].getName())
{
cout << "ERROR! Rectangle doesn't exist!" << endl << endl;
system("pause");
}
}
if(choice == 3)
{
for(i = 0; i < numRectangles; i++)
{
rect[i].findPerimeter();
cout << endl;
rect[i].findArea();
cout << endl;
}
}
if(choice == 4)
{
for(i = 0; i < numRectangles; i++)
{
rect[i].findWidth();
cout << endl;
rect[i].findHeight();
cout << endl;
}
}
if(choice == 5)
{
for(i = 0; i < numRectangles; i++)
{
rect[i].printGrid();
cout << endl;
}
}
if(choice == 6)
{
cout << "Bye bye!" << endl;
system("pause");
}
choice = rect[i].Menu();
return input;
} // End of while loop
inFile.close();
outFile.close();
return input;
}
ostream& operator<< (ostream& output, Rectangle grid)
{
return output;
}
main.cpp:
#include "Rectangle.h"
int main()
{
Rectangle rect[10];
int numRectangles;
for(int i = 0; i < numRectangles; i++)
{
cin >> rect[i];
cout << rect[i];
}
}
I did not check anything else other than getting it to compile. That means I am not sure if you have any bugs preventing it from running correctly. I also would advice you to avoid using using namespace std; in header files.

Overloading + operator with classes containing array pointers (C++)

I am currently writing a "Polynomial" class in order to practice Operator Overloading. I have successfully overloaded the stream extraction and insertion operators, but I am having some trouble with the "+" operator.
My class has a private pointer that proceeds to create an array in the constructor. I understand how one would overload the "+" operator with a complex number class, for example, but I'm getting confused with this program.
Guidance in finding a solution would be greatly appreciated.
Thank you.
#include<iostream>
#include<stdexcept>
using namespace std;
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
class Polynomial
{
friend istream& operator>>(istream& in, Polynomial& p);
friend ostream& operator<<(ostream& out, const Polynomial& p);
public:
Polynomial(int = 10);
~Polynomial();
void assignExponent();
Polynomial operator+(const Polynomial& other);
private:
int SIZE;
int *exponents;
int *polyPtr; //***************
};
#endif
//CONSTRUCTOR
Polynomial::Polynomial(int arraySize)
{
if(arraySize > 0)
SIZE = arraySize;
else
{
cout << "Array size must be greater than 0. Program will now "
<< "Terminate..." << endl;
system("pause");
exit(0);
}
polyPtr = new int[SIZE]; //*********************
exponents = new int[SIZE];
for(int i = 0; i<SIZE; i++)
polyPtr[i] = 0;
assignExponent();
};
//DESTRUCTOR
Polynomial::~Polynomial() //******************
{
delete [] polyPtr;
};
//STREAM INSERTION
istream& operator>>(istream& in, Polynomial& p)
{
for(int i = 0; i<p.SIZE; i++)
{
in >> p.polyPtr[i]; //*************
}
return in;
};
//STREAM EXTRACTION
ostream& operator<<(ostream& out, const Polynomial& p)
{
int exponent;
for(int i = 0; i<p.SIZE; i++)
{
exponent = (p.SIZE - 1) - i;
if(p.polyPtr[i] != 1)
{
if(exponent > 0 && exponent != 1)
out << p.polyPtr[i] << "x^" << exponent << " + ";
if(exponent == 1)
out << p.polyPtr[i] << "x" << " + ";
if(exponent == 0)
out << p.polyPtr[i];
}
//In order to not display coefficient if = 1
else
{
if(exponent > 0 && exponent != 1)
out << "x^" << exponent << " + ";
if(exponent == 1)
out << "x" << " + ";
if(exponent == 0)
out << p.polyPtr[i];
}
}
return out;
};
//Assigns a value for exponent
void Polynomial::assignExponent()
{
for(int i = 0; i<SIZE; i++)
{
exponents[i] = (SIZE - 1) - i;
}
};
//OVERLOAD OF + OPERATOR
Polynomial Polynomial::operator+(const Polynomial& other)
{
Polynomial sum(SIZE);
int difference;
//If the first polynomial is larger
if (SIZE > other.SIZE)
{
difference = SIZE - other.SIZE;
for(int i = 0; i<SIZE; i++)
{
if(i - difference < 0)
sum.polyPtr[i] = polyPtr[i];
else
{
sum.polyPtr[i] = polyPtr[i] +
other.polyPtr[i - difference];
}
}
}
//If the second polynomial is larger **PROBLEM**
if(other.SIZE > SIZE)
{
difference = other.SIZE - SIZE;
for(int i = 0; i<other.SIZE; i++)
{
if(i - difference < 0)
sum.polyPtr[i] = other.polyPtr[i];
else
{
sum.polyPtr[i] = other.polyPtr[i] +
polyPtr[i - difference];
}
}
}
//If the polynomials are equal
if(SIZE == other.SIZE)
{
for(int i = SIZE-1; i >= 0; i--)
{
sum.polyPtr[i] = polyPtr[i] + other.polyPtr[i];
}
}
return sum;
};
int main()
{
int polySize;
//User enters a size for the first & second polynomial
cout << "Enter a size for the first polynomial: ";
cin >> polySize;
Polynomial pOne(polySize);
cout << "\nEnter a size for the second polynomial: ";
cin >> polySize;
Polynomial pTwo(polySize);
//User enters in values (Overload of >> operator
cout << "\n\nEnter in values for the first polynomial, "
<< "in the format - (x x x x): " << endl;
cin >> pOne;
cout << "\nEnter in values for the second polynomial, "
<< "in the format - (x x x x): " << endl;
cin >> pTwo;
//Overload << operator for output
cout << "\nPolynomial 1 is: " << pOne << endl
<< "Polynomial 2 is: " << pTwo << endl;
Polynomial pThree = pOne + pTwo;
cout << "\nAfter being added together, the new polynomial is: "
<< pThree << endl;
system("pause");
}
I have updated my current code because I did not think opening another question would be the best way to go. Anyway, in trying to line up my polynomial's to be added, I've partially succeeded. The only problem that arises is when the second polynomial, pTwo, is larger than the first. I've labeled the section of code, PROBLEM. Thanks in advance.
I guess the + should write like below:
class Polynomial
{
// ...
Polynomial operator+(const Polynomial& other);
// ...
};
Polynomial Polynomial::operator+(const Polynomial& other)
{
Polynomial sum(SIZE);
for(int i = 0; i< SIZE; i++)
{
sum.polyPtr[i] = polyPtr[i] + other.polyPtr[i];
}
return sum;
}