Click here to Skip to main content
15,882,152 members
Articles / Programming Languages / C++
Tip/Trick

C++ -> Drawing Rectangles to Console

Rate me:
Please Sign up or sign in to vote.
4.83/5 (6 votes)
25 Aug 2011CPOL 51.7K   7   2
C++ -> Drawing Rectangles to Console
For drawing rectangles to console, I have two functions. It draws a rectangle with ASCII chars :)

One sets the cursor position. The second one draws the rectangle.

The code:

C++
//DrawRect.h
//Caner Korkmaz
#pragma once

//The libs
#include <iostream>
#include <Windows.h>

/*
 *This method sets the cursor position.
 *Usage:
 *setxy(1,1);
 */
BOOL setxy(int x, int y)
{
	COORD c = {x,y};
	return SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);
}

/*
 *This method draws the rectangle.
 *Usage:
 *DrawRect(1,1,10,10);
 *or
 *DrawRect(1,1,10,10,20,5);
 */
void DrawRect(int x, int y, int width, int height, int curPosX=0, int curPosY=0)
{
	setxy(x,y);cout << char(201);
	for(int i = 1; i < width; i++)cout << char(205);
	cout << char(187);
	setxy(x,height + y);cout << char(200);
	for(int i = 1; i < width; i++)cout << char(205);
	cout << char(188);
	for(int i = y + 1; i < height + y; i++)
	{
		setxy(x,i);cout << char(186);
		setxy(x + width,i);cout << char(186);
	}
	setxy(curPosX,curPosY);
}

Copy the code in a header file -> then use in your projects or games :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Turkey Turkey
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralThanks for reporting :) I was found the bug 2 days ago at my... Pin
Caner Korkmaz25-Aug-11 0:47
Caner Korkmaz25-Aug-11 0:47 
GeneralHello, good job!, just two bugs on your code: setxy(x,heig... Pin
Jose David Pujo25-Aug-11 0:27
Jose David Pujo25-Aug-11 0:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.