This solution may be 5 years late, but does correct the problems with the original program.
It checks that the user input is within acceptable values for the 80x24 output of a standard terminal and that the dimensions are positive. Big values are cropped to the max 80x24 chars and the absolute value of negative numbers entered are used.
NOTE: this program does NOT check if non integer values are entered.
Other than the user input verification, this solution rectifies the errors in the original code and uses c++'s std::endl instead of c's \n for a new line.
If you are only interested in the code to print the box look for the code after the comment:
//3. Print the box
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
int width = 0;
int height = 0;
// 1. Get User Input
//Introduction:
cout << "Welcome to the [Draw A Rectangle] program!" << endl;
cout << "This program will draw a rectangle in the application" << endl;
cout << "You will have to enter the width and the height"
<< " and it will draw it" << endl;
//User enters box width and height:
cout << "Please enter the width: ";
cin >> width;
cout << "Please enter the height: ";
cin >> height;
// 2. Verify Validity of User Input
// Height Max 24 width max 80 not zero or negative values
// 2a. check that width is not zero or negative.
if (width < 1) // zero or negative
{
if (width < 0)
{
cout << "A rectange must have a positive width [" << width
<< "] set to " << abs(width) << "." << endl;
width = abs(width);
}
else // width == zero
{
cout << "A rectangle must had a width of 1 or more."
<< " Width [" << width << "] set to 1." << endl;
width = 1;
}
}
// 2b. check that height is not zero or negative.
if (height < 1)
{
if (height < 0)
{
cout << "A rectange must have a positive height [" << height
<< "] set to " << abs(height) << "." <<endl;
height = abs(height);
}
else // height == zero
{
cout << "A rectangle must had a height of 1 or more."
<< " Height [" << height << "] set to 1." << endl;
height = 1;
}
}
// 2c. Limit to 80x24 chars.
// The standard vt100 terminal was only 80x24 chars
// 2c i) check width 80 or less
if (width > 80)
{
cout << "Width must be 80 or less. Width [" << width
<< "] limited to 80." << endl;
width = 80;
}
// 2c ii) check height 24 or less
if (height > 24 )
{
cout << "Height must be 24 or less. Height [" << height
<< "] limited to 24." << endl;
height = 24;
}
// 3. Print the box
//Prints the top dots (horizontal):
for (int dots = 0; dots < width; dots++)
{
cout << "*";
}
cout << endl;
//Prints the left dots (vertical):
// note first and last row are rows of dots
if (height > 1 )
{
for (int dots = 0; dots < height-2; dots++) // first row already printed
{
cout << setw(1) <<"*";
if (width > 1 )
{
cout << setw(width-1) << right << "*" << endl;
}
else
cout << endl;
}
//Prints the bottom dots (horizontal):
for (int dots = 0; dots < width; dots++)
{
cout<<"*";
}
cout << endl;
}
//Keeps program running:
cin.get();
}
Sceenshot