creating a hollow rectangle - c++

My assignment is to allow for user input of width, height, and character, in order to create a hollow rectangle. I am hitting a wall in my coding, For some reason, my rectangle doesn't have a "top" and the right side isn't on the correct column. I am fairly new to C++, so any criticism you may have is welcomed!
Below is my code and the output that I receive.
#include <iostream>
using namespace std;
int main()
{
int i, j, height, width;
char ch;
char cont ='Y';
while (cont=='Y' || cont=='y')
{
cout << "Enter desired height (3 to 20): ";
cin >> height;
while (height > 20 || height < 3 )
{
cout<<"Illegal entry. Please enter height value from 3 to 20: ";
cin >> height;
}
cout <<"Enter desired width (3 to 20): ";
cin >> width;
while (width > 20 || width < 3)
{
cout<<"Illegal entry. Please enter width value from 3 to 20: ";
cin >> width;
}
cout << "What character would you like to set as your border?: ";
cin >> ch;
for(int i = 1; i <= height; i++) {
if(width <= 1)
for(int i = 1; i <=width; i++) {
cout << " " << ch;
}
else if(i < height) {
cout << endl;
for(int j = 1; j <= width; j++) {
if(j == 1 || j == width)
cout << " " << ch;
else
cout << " ";
}
}
else {
cout<< endl;
for(int k = 1; k <= width; k++)
{
cout <<" "<< ch;
}
}
}
cout<<"\nDo you want to continue? (Y): ";
cin >> cont;
}
cout <<"\nYou are done here, good job.\n";
cout <<'\n';
}

While I won't get into the code itself, think about what you want to accomplish first, and then write the loops. (I suggest using row and col as variable names.)
Since you need a hollow rectangle and you are taking in a desired width and height we know the following (w and h being input amounts.)
So do the following prints in order:
You need a row of * with length w.
You need h - 2 rows of * that have w - 2 spaces between them.
You need another row like 1.
Do these in order and you will have your hollow rectangle.
Example input: w = 5, h = 7.
So we have:
***** // Step 1.
* * // Step 2. Note there are 5 - 2 spaces between them. (w - 2).
* *
* *
* *
* *
***** // Step 3.

While you already have a good answer, you are not making use of the C++ language functions that would make the task much easier, and more importantly, you are not validating your input correctly. For example, try the following:
> McNiel CSC 2050.exe
Enter desired height (3 to 20): No, I don't think I will
Things go wildly spinning out of control quickly.
Generally, when you want to validate user input and ensure you receive values within a specific range, you simply want a continual loop, where you prompt, validate the input, check/handle the stream states .eof(), .bad() and .fail() (see: std::basic_iostream) and empty any remaining characters in your input buffer before your next read attempt.
An example for your h x w input loop would be similar to the following (note, both h and w are read at the same time, you are free to use two loops if you like):
int h, w;
for (;;) {
std::cout << "enter height & width (3 <= h w <= 20): ";
if (!(std::cin >> h >> w)) {
if (std::cin.eof() || std::cin.bad()) {
std::cerr << "(user canceled/unrecoverable error)\n";
return 1;
}
else if (std::cin.fail()) {
std::cerr << "error: invalid integer input.\n";
std::cin.clear();
std::cin.ignore (std::numeric_limits<std::streamsize>::max(),'\n');
}
}
else if (3 <= h && h <=20 && 3 <= w && w <= 20)
break;
else
std::cerr << "error: h or w not within (3 <= x <= 20)\n";
}
See std::basic_istream::ignore for details on emptying the input stream and std::basic_ios::clear.
Next, rather than some loop scheme outputting spaces, you simply need to make use of std::setw to handle the spacing between the '*' to make your hollow rectangle. The top and bottom are solid, but for the middle rows, all you need to do is std::cout << '*' << std:setw(w-1) << '*';. For example your entire output loop reduces to:
for (int i = 0; i < h; i++) {
if (!i || i == h - 1)
for (int j = 0; j < w; j++)
std::cout << '*';
else
std::cout << '*' << std::setw(w-1) << '*';
std::cout << '\n';
}
Putting it altogether, you can do something similar to the following:
#include <iostream>
#include <iomanip>
#include <limits>
int main (void) {
int h, w;
for (;;) {
std::cout << "enter height & width (3 <= h w <= 20): ";
if (!(std::cin >> h >> w)) {
if (std::cin.eof() || std::cin.bad()) {
std::cerr << "(user canceled/unrecoverable error)\n";
return 1;
}
else if (std::cin.fail()) {
std::cerr << "error: invalid integer input.\n";
std::cin.clear();
std::cin.ignore (std::numeric_limits<std::streamsize>::max(),'\n');
}
}
else if (3 <= h && h <=20 && 3 <= w && w <= 20)
break;
else
std::cerr << "error: h or w not within (3 <= x <= 20)\n";
}
for (int i = 0; i < h; i++) {
if (!i || i == h - 1)
for (int j = 0; j < w; j++)
std::cout << '*';
else
std::cout << '*' << std::setw(w-1) << '*';
std::cout << '\n';
}
}
Example Use/Output
$ ./bin/hollowrect
enter height & width (3 <= h w <= 20): No, I don't think I will
error: invalid integer input.
enter height & width (3 <= h w <= 20): OK
error: invalid integer input.
enter height & width (3 <= h w <= 20): 10 2
error: h or w not within (3 <= x <= 20)
enter height & width (3 <= h w <= 20): 10 3
***
* *
* *
* *
* *
* *
* *
* *
* *
***
A second h x w example:
$ ./bin/hollowrect
enter height & width (3 <= h w <= 20): 3 10
**********
* *
**********
User cancels with manual EOF:
$ ./bin/hollowrect
enter height & width (3 <= h w <= 20): help
error: invalid integer input.
enter height & width (3 <= h w <= 20): (user canceled/unrecoverable error)
Look things over and let me know if you have further questions.

if you want to below result when assign height and width is 4.
* * * *
* *
* *
* * * *
your for loop is wrong, using this code in your for loop.
for(int i = 1; i <= height; i++) {
if( i == 1 || i == height) {
for (int j = 1; j <= width; j++) {
std::cout << ch << " ";
}
std::cout << std::endl;
} else {
for (int j = 1; j <= width; j++) {
if( j == 1 || j == width) {
std::cout << ch << " ";
} else {
std::cout << " ";
}
}
std::cout << std::endl;
}
}

Related

Accelerated C++ Exercise 2.4

I've been following Accelerated C++ for a couple of weeks now but I have been stuck at exercise 2.4 for a while and finally I thought I found it out but after trying giving it different dimensions I found out that it doesn't really work and I don't really understand why
The code initially prints a framed message, in this particular exercises I was supposed to change how the code prints the blanks from one character at a time into writing all the planks at once
here is the code:
// [2-0, 2-4] Exercises
#include<iostream>
#include<string>
// saying what standard-library names we use
using std::cout; using std::endl;
using std::cin; using std::string;
int main()
{
// asking for the name
cout << "Please enter your first name: ";
// reading the name
string name;
cin >> name;
// building the message that we intend to write
const string greeting = "Hello, " + name + "!";
// 2.2 & 2.3 asking for inpadY
cout << "Please enter the number of padY (Vertical padding): ";
// 2.2 & 2.3 reading the inpadY
int inpadY;
cin >> inpadY;
// 2.2 & 2.3 asking for inpadX
cout << "Please enter the number of padX (Horizontal padding): ";
// 2.2 & 2.3 reading the inpadX
int inpadX;
cin >> inpadX;
// the number of planks surrounding the greeting
// 2.2 & 2.3 added inpadY as the number of planks;
const int padY = inpadY;
// 2.2 & 2.3 added inpadX
const int padX = inpadX;
// 2.4 pad size
const int pad = inpadX + inpadY;
// the number of rows and columns to write
const int rows = padY * 2 + 3;
const string::size_type cols = greeting.size() + padX * 2 + 2;
// 2.4 creating a padding string left and right and top and bottom
const string LeftRightPad(padY, ' ');
const string TopBottomPad(cols - 2, ' ');
// write a blank line to separate the output and the input
cout << endl;
// write rows rows of output
// invariant: we have written r rows so far
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
// invariant: we have written c characters so far in the current row
while (c != cols) {
// is it time to write the greeting?
if (r == padY + 1 && c == padX + 1)
{
cout << greeting;
c += greeting.size();
} else {
// are we on the border?
if (r == 0 || r == rows - 1 ||
c == 0 || c == cols - 1)
{cout << "*";
++c;}
else
// 2.4 typing out the spaces at once
{cout << LeftRightPad;
c += LeftRightPad.size();}
}
}
cout << endl;
}
return 0;
}
Edited to have the input and output
Please enter your first name: Estrogen
Please enter the number of padY (Vertical padding): 2
Please enter the number of padX (Horizontal padding): 2
**********************
* *
* *
* Hello, Estrogen! *
* *
* *
**********************
Process returned 0 (0x0) execution time : 3.281 s
Press any key to continue.
Please enter your first name: Estrogen
Please enter the number of padY (Vertical padding): 2
Please enter the number of padX (Horizontal padding): 5
****************************
* *
* *
* *
* *
* *
****************************
Process returned 0 (0x0) execution time : 5.098 s
Press any key to continue.
Please enter your first name: Estrogen
Please enter the number of padY (Vertical padding): 3
Please enter the number of padX (Horizontal padding): 2
**********************
*
*
*
*
*
*
*
**********************
Process returned 0 (0x0) execution time : 4.333 s
Press any key to continue.
Update: I've rewritten the code and the output is an infinite loop of asterisks here is the new code
#include<iostream>
#include<string>
using std::string; using std::endl;
using std::cout; using std::cin;
int main()
{
cout << "Please enter your first name: ";
string name;
cin >> name;
const string message = "Hello, " + name + "!";
cout << "Enter the length: ";
int length;
cin >> length;
cout << "Enter the height: ";
int height;
cin >> height;
const int rows = height * 2 + 3;
const string::size_type cols = message.size() + length * 2 + 2;
const string TopBottom(cols, '*');
const string Blank(cols - 2, ' ');
const string messageblank(cols - 3 - message.size(), ' ');
cout << endl;
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
while (c != cols) {
if ( r == height + 1 && c == length + 1)
{
cout << messageblank << message << messageblank;
c += Blank.size();
} else
if (r == 0 && c == 0 || r == rows - 1 && c == cols -1)
{
cout << TopBottom;
c += TopBottom.size();
} else
if ( r != 0 && c == 0 || r != rows -1 && c == cols - 1)
{
cout << "*";
++c;
} else
cout << Blank;
c += Blank.size();
}
cout << endl;
}
return 0;
}
Thank you guys for help in advance
Unless the code is supposed to be written this way, I would propose another, row by row approach:
print_frame_row(cols);
for (int i = 0; i < padY; ++i)
print_v_padding(cols);
print_greeting(padX, greeting);
for (int i = 0; i < padY; ++i)
print_v_padding(cols);
print_frame_row(cols);
where
void print_frame_row(int cols)
{
std::cout << std::string(cols, '*') << '\n';
}
void print_v_padding(int cols)
{
const std::string h_padding(cols - 2, ' ');
std::cout << '*' << h_padding << "*\n";
}
void print_greeting(int padX, const std::string &msg)
{
const std::string h_padding(padX, ' ');
std::cout << '*' << h_padding << msg << h_padding << "*\n";
}
This way you have a simpler logic, and need not worry about counting columns or deciding when to write each character.
ok so it took me 3 days but I finally figured it out here is the working code
#include<iostream>
#include<string>
using std::string; using std::endl;
using std::cout; using std::cin;
int main()
{
cout << "Please enter your first name: ";
string name;
cin >> name;
cout << "Enter the length: ";
int length;
cin >> length;
cout << "Enter the height: ";
int height;
cin >> height;
const string message = "Hello, " + name + "!";
const int rows = height * 2 + 3;
const string::size_type cols = message.size() + length * 2 + 2;
const string TopBottom(cols, '*');
const string Blank(cols - 2, ' ');
const string messageblank(length, ' ');
cout << endl;
for (int r = 0; r != rows; ++r) {
string::size_type c = 0;
while (c != cols) {
if ( r == height + 1 && c == 0)
{
cout << "*" << messageblank << message << messageblank << "*";
c += TopBottom.size();
} else
if (r == 0 && c == 0 || r == rows - 1 && c == 0)
{
cout << TopBottom;
c += TopBottom.size();
} else
if ( c == 0 && r != 0 || c == 0 && r != rows - 1)
{
cout << "*" << Blank << "*";
c += TopBottom.size();
}
}
cout << endl;
}
return 0;
}

C++: How do I make this shape from this code?

I am trying to make this shape from the code below. I'm confused as to how to make it print the 2nd row, second to last star without it skipping and printing the extra space before printing the star. Once that is figured out would the bottom half, when the stars expands back out, would the code be similar to the top half? I have tried a couple combinations of code between c and r but I have been stuck with what I currently.
---------------------- //row 0
* *| //row 1
* * * *| //row 2
* * * * * *|
* * * * * * * *|
* * * * * * * * * *|
* * * * * * * * * * *|
* * * * * * * * * *|
* * * * * * * *|
* * * * * *|
* * * *|
* *|
----------------------
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 38 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl << endl;
for (int r = 0; r < num; ++r) //outer loop/rows
{
for (int c = 0; c < num; ++c) //inner loop/columns
{
if (r == 0) cout << "--"; //top of square
else if (c >= r + r - c && c < num - 1)
cout << " ";
//else if (c == num - 1) cout << "*|";
else if (r == num - 1) cout << "--"; //bottom of square
else if (c == num - 1) cout << "*|"; //right side of square
else if (r > c) cout << "* ";
}
cout << endl;
}
break;
}
else cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
I just took two variables left=0 & right=num-1 and increased left & decreased right till r<=num/2, after that i reversed the process,when the col <= left or col >=right I printed *.
I hope it will be easy to understand.
Here is the code:
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 38 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl << endl;
int left=0,right=num-1;
//for printing top line
for(int i = 0; i < num; i++) cout<<"- ";
cout<<"-"<<endl;
for (int r = 0; r < num; ++r) //outer loop/rows
{
//printing columns
for(int c = 0; c < num; c++)
{
if(c <= left || c >= right)
cout<<"* ";
else
cout<<" ";
}
if(r >= num/2) //checking for half of the rows
{
left--;right++;
}
else
{
left++;right--;
}
cout<<"|"<<endl;
}
//for printing last additional line
for(int i = 0; i < num; i++) cout<<"- ";
cout<<"-"<<endl;
break;
}
else cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
This approach does it the math way.
Furthermore it draws a full frame with plus-chars at the edges.
Give it a try.
#include <iostream>
#include <cmath>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a) {
cin >> num;
if (num < 40 && num > 0 && num % 2 == 1) {
cout << "Thank you!" << endl << endl;
int center = ceil(num / 2.0);
for (int r = 0; r <= num+1; ++r) { //outer loop/rows
for (int c = 0; c <= num+1; ++c) { //inner loop/columns
if (r == 0 || r == num+1) {
if (c == 0 || c == num+1)
cout << "+"; // corner
else
//top or botton of square between corners
if (c == center)
cout << "-";
else
cout << "--";
}
else if (c == 0 || c == num+1) {
cout << "|"; // left or right frame
} else {
// inner part
if ((center-std::abs(center-r)) >= center-std::abs(center-c))
if (c < center)
cout << "* ";
else if (c > center)
cout << " *";
else
cout << "*";
else
if (c == center)
cout << " ";
else
cout << " ";
}
}
cout << endl;
}
} else
cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
Just another way (with some more user input checking):
#include <iostream>
#include <string>
#include <limits>
#include <sstream>
using std::cout;
using std::cin;
using std::string;
const auto ssmax = std::numeric_limits<std::streamsize>::max();
const int max_dim = 40;
const int max_iter = 3;
int main() {
cout << "Enter a positive odd number less than " << max_dim << ": ";
int num = 0, counter = 0;
while ( counter < max_iter ) {
cin >> num;
if ( cin.eof() )
break;
if ( cin.fail() ) {
cout << "Please, enter a number!\n";
cin.clear();
cin.ignore(ssmax,'\n');
}
if ( num < max_dim && num > 0 && num % 2 ) {
cout << "Thank you!\n\n";
//top line
string line(num * 2, '-');
cout << line << '\n';
for ( int r = 0, border = num - 1; r < num; ++r ) {
cout << '*';
for ( int c = 1; c < num; ++c ) {
if ( (c > r && c < border) || (c < r && c > border) )
cout << " ";
else
cout << " *";
}
// right border
cout << "|" << '\n';
--border;
}
//bottom line
cout << line << '\n';
++counter;
} else {
cout << "Please, enter a positive odd number that is less than 40!\n";
}
}
cout << std::endl;
}
Or my favorite:
// top line
string line = string(num * 2, '-') + '\n';
cout << line;
// inside lines
int r = 0, border = ( num - 1 ) * 2;
string inside = string(border + 1, ' ') + "|\n";
// top
while ( r < border ) {
inside[r] = '*';
inside[border] = '*';
r += 2;
border -= 2;
cout << inside;
}
// center line
inside[r] = '*';
cout << inside;
// bottom
while ( border > 0 ) {
inside[r] = ' ';
inside[border] = ' ';
r += 2;
border -= 2;
cout << inside;
}
//bottom line
cout << line;

Dynamic array error in Conways Game of Life

I am working on a program that emulates conways game of life, and it works perfectly with the preset dimensions. However, once i try to use the dynamic dimensions as seen in option e, i start having problems. The main problem is in the "life" function which iterates throughout the array and decides if it should bring to life a cell. I have been debugging for a while and it i enter the dimensions as 50*40, it iterates until 61, 1. This should technically work but it just breaks everytime. Keep in mind that I add 12 to each dimension to account for the buffer zone I put around the edges. Technically it should work then right? If you have any suggestions I would really appreciate it!
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <new> // i havent used this one yet
#include <cmath>
using namespace std;
// REMEMBER: The outside of the array is 6 more than what we show so that nothing interferes
//also that it goes y,x and that x is going to be bigger so that we get a rectange
//we use the copy function to copy an array from eachother, either the current one to the temp one or
//vise versa. This is so that we can alter the cells one step at a time without affecting everything else.
void copy(int **array1, int **array2, int o, int p)
{
for(int j = 0; j < o; j++)
{
for(int i = 0; i < p; i++)
array2[j][i] = array1[j][i];
}
} // the second array sent is assigned the first array sent!
//this array will initialize our arrays so that we can use them later
int** init(int n, int m)
{
int **array;
array = new int*[m]; // x
array = new int*[n]; // y
for (int q=0; q < n; q++)
{
array[q] = new int[n];
for (int w=0; w < m; w++)
{
array[w] = new int[m];
}
}
return array;
}
void populate(int o, int p, int** board){ // THIS FUNCTION HASN'T BEEN USED YET
for(int i=0; i < p; i++)
{
for(int j=0; j < o; j++) // It was in a in-class demo but i dont think i need it
{
board[i][j] = pow(i, j);
}
}
}
//The life function looks at the pieces around the cell and figures out what happens next.
// Probably the most important in the entire program, feast your eyes!
void life(int **array, int o, int p)
{
//Copies the main array to a temp array so changes can be made without affecting anyone else
int **temp;
temp = init(o, p);
copy(array, temp, o, p);
for(int j = 1; j < o; j++)
{
for(int i = 1; i < p; i++)
{
// checks all 8 cells surrounding it
int count = 0;
cout << " j is " << j << " and i is " << i << endl;
// cout << array[j][i]; // DEBUGGING
count =
array[j-1][i] + array[j-1][i-1] +
array[j][i-1] + array[j+1][i-1] +
array[j+1][i] + array[j+1][i+1] +
array[j][i+1] + array[j-1][i+1];
//cell dies.
if(count < 2 || count > 3)
{
temp[j][i] = 0;
}
//nothing happens.
if(count == 2)
{
temp[j][i] = array[j][i];
}
//now the cell will be born, or if it already is alive then it stays that way.
if(count == 3)
{
temp[j][i] = 1;
}
}
}
//Copies the temp array back to the main array.
copy(temp, array, o, p);
}
//This function prints the 40 x 50 part of the array, a 1 means that there will be a cell there,
//otherwise it will just be an empty space.
void print(int **array, int o, int p)
{
// WE ONLY CHECK WHAT WE SEE, WHICH IS 6 LESS THAN THE ARRAY!!!
for(int j = 6; (j < (o-6)); j++)
{
for(int i = 6; (i < (p-6)); i++)
{
if(array[j][i] == 1 )
cout << '*';
else
cout << '.';
}
cout << endl;
}
}
//I read somewhere it would be a good idea to make sure to end the program early if it somehow
//became stable by itself early. so this compares the old array with the new one to check if they
//are the same. This commonly occurs if a glider runs off the screen for example.
bool compare(int **array1, int **array2,int o,int p)
{
int counter = 0;
for(int j = 0; j < o; j++)
{
for(int i = 0; i < p; i++)
{
if(array1[j][i]==array2[j][i])
counter++;
}
}
if(counter == o*p)
return true;
else
return false;
}
int main()
{
int o= 52, p=62;
int **firstgen;
int **next;
int **backup;
// 40 + 12, 50 + 12
int x, y;
char starty;
char again;
char cont;
bool comparison;
//Here is where we initialize our arrays
firstgen = init(o,p);
next = init(o,p);
backup = init(o,p);
cout << endl << "Welcome to John Conway's Game of Life." << endl;
//This loop is for if we are still simulating, don't get confused!
do
{
//this loop checks for inputs.
do
{
menu: //this is a goto we use for if we change dimensions
x = 0, y = 0;
//now we get the menu
cout << endl << "--- Choose an option Below ---" << endl;
cout << "(a) Glider" << endl;
cout << "(b) Gosper Gilder gun" << endl;
cout << "(c) R Pentomino Pattern" << endl;
cout << "(d) Oscillator" << endl;
cout << "(e) Change the dimensions (it defaults to (50*40)" << endl;
cin >> starty;
}while(starty != 'a' && starty != 'b' && starty != 'c' && starty != 'd' && starty != 'e');
int i = 0;
//we need to assign firstgen in this area
//choose a glider position
if (starty == 'a'){
x= 0, y= 0;
cout << " X dimension: ";
cin >> x;
cout << " Y dimension: ";
cin >> y;
if (x < 0 || x > p || y < 0 || y > o){
cout << endl << "you entered invalid dimensions" << endl;
goto menu;
}
x = x+6; //we add 6 because there are six spots to the left that aren't shown we need to account for
y = y+6;
//creates the glider
firstgen[y][x] = 1;
firstgen[y][x+1] = 1;
firstgen[y][x+2] = 1;
firstgen[y-1][x] = 1;
firstgen[y-2][x+1] = 1;
}
else if (starty == 'b'){
x= 0, y= 0;
cout << "Your dimensions are based on the farthest left point" << endl;
cout << " X dimension: ";
cin >> x;
cout << " Y dimension: ";
cin >> y;
if (x < 0 || x > p || y < 0 || y > o){
cout << endl << "you entered invalid dimensions" << endl;
goto menu;
}
//this is because we have the buffer zone of 6
x = x+6;
y = y+6;
//Gosper gun
//box on left
firstgen[y][x] = 1;
firstgen[y][x+1] = 1;
firstgen[y+1][x] = 1;
firstgen[y+1][x+1] = 1;
//left circle starting in top of the left curve (flat part)
firstgen[y][x+10] = 1;
firstgen[y-1][x+11] = 1;
firstgen[y-2][x+12] = 1;
firstgen[y-2][x+13] = 1;
firstgen[y+1][x+10] = 1;
firstgen[y+2][x+10] = 1;
firstgen[y+3][x+11] = 1;
firstgen[y+4][x+12] = 1;
firstgen[y+4][x+13] = 1;
//dot in middle
firstgen[y+1][x+14] = 1;
//arrow thing on the right
firstgen[y-1][x+15] = 1;
firstgen[y][x+16] = 1;
firstgen[y+1][x+16] = 1;
firstgen[y+1][x+17] = 1;
firstgen[y+2][x+16] = 1;
firstgen[y+3][x+15] = 1;
//boomerang bit on the far right section
firstgen[y][x+20] = 1;
firstgen[y][x+21] = 1;
firstgen[y-1][x+20] = 1;
firstgen[y-1][x+21] = 1;
firstgen[y-2][x+20] = 1;
firstgen[y-2][x+21] = 1;
firstgen[y-3][x+22] = 1;
firstgen[y-3][x+24] = 1;
firstgen[y-4][x+24] = 1;
firstgen[y+1][x+22] = 1;
firstgen[y+1][x+24] = 1;
firstgen[y+2][x+24] = 1;
//tiny box on farthest right, almost done!
firstgen[y-1][x+34] = 1;
firstgen[y-1][x+35] = 1;
firstgen[y-2][x+34] = 1;
firstgen[y-2][x+35] = 1;
}
else if (starty == 'c')
{
x= 0, y= 0;
cout << "Your dimensions are based on the farthest left point" << endl;
cout << " X dimension: ";
cin >> x;
cout << " Y dimension: ";
cin >> y;
if (x < 0 || x > p || y < 0 || y > o){
cout << endl << "you entered invalid dimensions" << endl;
goto menu;
}
x = x+6;
y = y+6;
//creates R Pentamino pattern
firstgen[y][x] = 1;
firstgen[y][x+1] = 1;
firstgen[y+1][x+1] = 1;
firstgen[y-1][x+1] = 1;
firstgen[y-1][x+2] = 1;
}
// creates the simple oscillator
else if (starty == 'd')
{
x= 0, y= 0;
cout << "Your dimensions are based on the top of the oscillator" << endl;
cout << " X dimension: ";
cin >> x;
cout << " Y dimension: ";
cin >> y;
if (x < 0 || x > p || y < 0 || y > o){
cout << endl << "you entered invalid dimensions" << endl;
goto menu;
}
x = x+6;
y = y+6;
firstgen[y][x] = 1;
firstgen[y+1][x] = 1;
firstgen[y+2][x] = 1;
}
// allows you to choose your dimensions
else if (starty == 'e')
{
o= 0, p= 0;
x= 0, y= 0;
cout << "choose the height and width of your field, between 0 and 100" << endl;
cout << " X dimension: ";
cin >> x;
cout << " Y dimension: ";
cin >> y;
if (x < 0 || x > 100 || y < 0 || y > 100){
cout << endl << "Please keep dimensions between 0 and 100" << endl;
goto menu;
}
// the problem is that it is adding my x dimension and my placement choice together and then
// starts to run the program, which threadbreaks. I need to find out why these two values are
// adding together and fix it
x = x+12;
y = y+12; // plus twelve so that we have 6 around all sides
p = x;
o = y;
firstgen = init(o,p);
next = init(o,p);
backup = init(o,p);
// is this part below necessary?
//firstgen[o][p];
// next[o][p];
// backup[o][p];
// idk
// cout << "y value is: " << o << " and the x value is " << p << endl; // debugging
goto menu;
}
//Loop that does the simulation.
do
{
//Prints the generation. If i == 0, the firstgen array is copied to the
//next array, and is printed before any functions act upon it.
cout << endl << "Generation " << i << ":" << endl << endl;
//Initializes the arrays by copying the firstgen array to the next array.
if(i == 0)
copy(firstgen, next, o, p);
//this stuff below happens in every cycle
cout << "the x/p value is" << p << "and the y/o value is " << o << endl;
copy(next, backup, o, p);
print(next, o, p);
life(next, o, p);
i++;
//Pauses the system .2 seconds so that it doesn't flash past you super fast and you
// can't appreciate its beauty
system("sleep .2");
//Checks whether the generation is a multiple of 100 to ask
//the user if they want to continue
if(i % 100 == 1 && i != 1)
{
cout << endl;
//Loop to check for proper inputs.
do
{
cout << "Continue? (y or n): ";
cin >> cont;
}while(cont != 'y' && cont != 'n');
if(cont == 'n')
break;
}
//Compares the current generation with a backup generation.
//The idea is that if it is the same with the backup generation then
//something boring is going on or smething went wrong. It will end if that
//is the case.
comparison = compare(next, backup, o, p);
if(comparison == false)
// system("clear");
//cout << string( 10, '\n' );
if(comparison == true)
cout << endl;
}while(comparison == false);
//Loop to check if we want to keep going.
do
{
cout << "Run another Simulation? (y or n): ";
cin >> again;
}
while(again != 'y' && again != 'n');
//this is where we clean out all our firstgen values
//i used to have this at the top but didn't really need it
for(int y = 0; y < o; y++)
{
for(int x = 0; x < p; x++)
{
firstgen[y][x] = 0;
}
}
}
while(again == 'y');
return 0;
}
I figured it out!
The thing to take away from this is to make sure that your initiation function creates the array with the same size as the one you will be accessing. I was trying to get values from array[52][1] which didn't exist because in my init function i only had the for loop running while n < o, which means it didn't create the 52nd row. what a relief!

How to make exception in for loop?

The code below prints a box with the intergers the user inputs. I need to make it hollow to only display the full length of the first and last line of the box. like width = 5 height = 4
Example Output:
00000
0 0
0 0
00000
Source:
int main ()
{
int height;
int width;
int count;
int hcount;
string character;
cout << "input width" << endl;
cin >> width;
cout << "input height" << endl;
cin >> height;
cout << "input character" << endl;
cin >> character;
for (hcount = 0; hcount < height; hcount++)
{
for (count = 0 ; count < width; count++)
cout << character;
cout << endl;
}
}
I do not know how to change the loop condition for the width to make it work.
I think you can test whether you are in the first or last row, and first or last column.
Example:
#include <string>
#include <iostream>
int main ()
{
using namespace std; // not recommended
int height;
int width;
string character;
cout << "input width" << endl;
cin >> width;
cout << "input height" << endl;
cin >> height;
cout << "input character" << endl;
cin >> character;
for (int i = 0; i < height; i++)
{
// Test whether we are in first or last row
std::string interior_filler = " ";
if (i == 0 || i == height - 1)
{
interior_filler = character;
}
for (int j = 0; j < width; j++)
{
// Test whether are in first or last column
if (j == 0 || j == width -1)
{
cout << character;
} else {
cout << interior_filler;
}
}
// Row is complete.
cout << std::endl;
}
}
Here is the output:
$ ./a.out
input width
10
input height
7
input character
*
OUTPUT
**********
* *
* *
* *
* *
* *
**********
Add an if to the cout << character line. If we're not in the first row or column, output a space instead of the character.

Convert integers to characters [duplicate]

This question already has answers here:
How to convert a number to string and vice versa in C++
(5 answers)
Closed 9 years ago.
I am trying to get my program to print letters instead of numbers. I used char c = static_cast<char>(N); to attempt to do this but it wont work, instead it prints character images that are not (a-z) How can I get the numbers to be printed as letters?
#include <cstdlib>
#include <iostream>
using namespace std;
// Function getUserInput obtains an integer input value from the user.
// This function performs no error checking of user input.
int getUserInput()
{
int N(0);
cout << endl << "Please enter a positive, odd integer value, between (1-51): ";
cin >> N;
if (N < 1 || N > 51 || N % 2 == 0)
{
cout << "Error value is invalid!" << "\n";
cout << endl << "Please enter a positive, odd integer value, between (1-51): ";
cin >> N;
system("cls");
}
cout << endl;
return N;
} // end getUserInput function
// Function printDiamond prints a diamond comprised of N rows of asterisks.
// This function assumes that N is a positive, odd integer.
void printHourglass(int N)
{
char c = static_cast<char>(N);
for (int row = (N / 2); row >= 1; row--)
{
for (int spaceCount = 1; spaceCount <= (N / 2 + 1 - row); spaceCount++)
cout << ' ';
for (int column = 1; column <= (2 * row - 1); column++)
cout << c;
cout << endl;
} // end for loop
// print top ~half of the diamond ...
for (int row = 1; row <= (N / 2 + 1); row++)
{
for (int spaceCount = 1; spaceCount <= (N / 2 + 1 - row); spaceCount++)
cout << ' ';
for (int column = 1; column <= (2 * row - 1); column++)
cout << c;
cout << endl;
} // end for loop
// print bottom ~half of the diamond ...
return;
} // end printDiamond function
int main()
{
int N = 1;
while (N == 1)
{
printHourglass(getUserInput());
cout << endl;
cout << "Would you like to print another hourglass? ( 1 = Yes, 0 = No ):";
cin >> N;
}
} // end main function
The letters are not numbered with A starting at 1 or anything like that. You're likely on an ASCII/UTF-8 system. So, in printHourglass, replace cout << N with
cout << static_cast<char>('A' + count - 1);
C functions, itoa
C++, using stringstream
boost::lexical_cast
Actually for your case, you can directly print it out. cout << N