Saturday, May 22, 2010

C++ box application?

the application should run like:


how big: 5 %26lt; user input





* * * * *


*space*


*space*


*space*


* * * * *





Ignore the space











#include %26lt;iostream.h%26gt;





int main()


{


int size;





cout %26lt;%26lt; "How Big? ";


cin %26gt;%26gt; size = 444;





for(int i = 1; i %26lt;= size; i++)


{


for(int i = 1; i %26lt; size; i++)


{


cout %26lt;%26lt; "* ";


}





cout %26lt;%26lt; "*" %26lt;%26lt; endl;


}





return(0);


}

C++ box application?
I didn't try to run your code, but it looks like it won't work. I see you want to print spaces in between the stars in the top and bottom edges of the box. This is good, since it'll give you a better looking box, but it makes the code a bit more complicated than it would be with a solid top and bottom (which would look like a rectangle on the terminal).





The first thing to realize is that you're only doing two different things: printing the top/bottom, or printing the rest of it. To avoid duplicating code, you could create a function like this:





void horizSide(const int len, const char c, const char spacer) {


for (int i = 0; i %26lt; len-1; i++) {


cout %26lt;%26lt; c %26lt;%26lt; spacer;


}


cout %26lt;%26lt; c %26lt;%26lt; endl;


}





Then your algorithm is: call horizSide to print top, print middle of box, call horizSide to print bottom.





If you define:





const char star('*');


const char spacer(' ');





then the only line you need in the loop between calls to horizSide is:





cout %26lt;%26lt; star %26lt;%26lt; setw(size*2-2) %26lt;%26lt; setfill(spacer) %26lt;%26lt; star %26lt;%26lt; endl;





Note that I defined horizSide as I did so you can use some other spacer character and it'll still look right.





I'll let you code the loop and put it all together. You should be displaying a nice looking box in no time.

marguerite

No comments:

Post a Comment