As in the title. How can I clear console in C++?
For pure C++
You can't. C++ doesn't even have the concept of a console.
The program could be printing to a printer, outputting straight to a file, or being redirected to the input of another program for all it cares. Even if you could clear the console in C++, it would make those cases significantly messier.
See this entry in the comp.lang.c++ FAQ:
https://isocpp.org/wiki/faq/input-output#clear-screen
OS-Specific
If it still makes sense to clear the console in your program, and you are interested in operating system specific solutions, those do exist.
For Windows (as in your tag), check out this link:
How do we clear the console in assembly?
Edit: This answer previously mentioned using system("cls");, because Microsoft said to do that. However it has been pointed out in the comments that this is not a safe thing to do. I have removed the link to the Microsoft article because of this problem.
Libraries (somewhat portable)
ncurses is a library that supports console manipulation:
http://www.gnu.org/software/ncurses/ (runs on Posix systems)
http://gnuwin32.sourceforge.net/packages/ncurses.htm (somewhat old Windows port)
For Windows, via Console API:
void clear() {
COORD topLeft = { 0, 0 };
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen;
DWORD written;
GetConsoleScreenBufferInfo(console, &screen);
FillConsoleOutputCharacterA(
console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
FillConsoleOutputAttribute(
console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
SetConsoleCursorPosition(console, topLeft);
}
It happily ignores all possible errors, but hey, it's console clearing. Not like system("cls") handles errors any better.
For *nixes, you usually can go with ANSI escape codes, so it'd be:
void clear() {
// CSI[2J clears screen, CSI[H moves the cursor to top-left corner
std::cout << "\x1B[2J\x1B[H";
}
Using system for this is just ugly.
The easiest way for me without having to reinvent the wheel.
void Clear()
{
#if defined _WIN32
system("cls");
//clrscr(); // including header file : conio.h
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
system("clear");
//std::cout<< u8"\033[2J\033[1;1H"; //Using ANSI Escape Sequences
#elif defined (__APPLE__)
system("clear");
#endif
}
On Windows you can use "conio.h" header and call clrscr function to avoid the use of system funtion.
#include <conio.h>
clrscr();
On Linux you can use ANSI Escape sequences to avoid use of system function. Check this reference ANSI Escape Sequences
std::cout<< u8"\033[2J\033[1;1H";
On MacOS
Investigating...
For Linux/Unix and maybe some others but not for Windows before 10 TH2:
printf("\033c");
will reset terminal.
outputting multiple lines to window console is useless..it just adds empty lines to it.
sadly, way is windows specific and involves either conio.h (and clrscr() may not exist, that's not a standard header either) or Win API method
#include <windows.h>
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,
(TCHAR) ' ',
cellCount,
homeCoords,
&count
)) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,
csbi.wAttributes,
cellCount,
homeCoords,
&count
)) return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
For POSIX system it's way simpler, you may use ncurses or terminal functions
#include <unistd.h>
#include <term.h>
void ClearScreen()
{
if (!cur_term)
{
int result;
setupterm( NULL, STDOUT_FILENO, &result );
if (result <= 0) return;
}
putp( tigetstr( "clear" ) );
}
// #define _WIN32_WINNT 0x0500 // windows >= 2000
#include <windows.h>
#include <iostream>
using namespace std;
void pos(short C, short R)
{
COORD xy ;
xy.X = C ;
xy.Y = R ;
SetConsoleCursorPosition(
GetStdHandle(STD_OUTPUT_HANDLE), xy);
}
void cls( )
{
pos(0,0);
for(int j=0;j<100;j++)
cout << string(100, ' ');
pos(0,0);
}
int main( void )
{
// write somthing and wait
for(int j=0;j<100;j++)
cout << string(10, 'a');
cout << "\n\npress any key to cls... ";
cin.get();
// clean the screen
cls();
return 0;
}
To clear the screen you will first need to include the following header:
#include <stdlib.h>
this will import windows commands. Then you can use the 'system' function to run Batch commands (which edit the console). On Windows in C++, the command to clear the screen would be:
system("CLS");
And that would clear the console. The entire code would look like this:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
system("CLS");
}
And that's all you need! Goodluck :)
In Windows:
#include <cstdlib>
int main() {
std::system("cls");
return 0;
}
In Linux/Unix:
#include <cstdlib>
int main() {
std::system("clear");
return 0;
}
This is hard for to do on MAC seeing as it doesn't have access to the windows functions that can help clear the screen. My best fix is to loop and add lines until the terminal is clear and then run the program. However this isn't as efficient or memory friendly if you use this primarily and often.
void clearScreen(){
int clear = 5;
do {
cout << endl;
clear -= 1;
} while (clear !=0);
}
Use system("cls") to clear the screen:
#include <stdlib.h>
int main(void)
{
system("cls");
return 0;
}
In Windows we have multiple options :
clrscr() (Header File : conio.h)
system("cls") (Header File : stdlib.h)
In Linux, use system("clear") (Header File : stdlib.h)
If you're on Windows:
HANDLE h;
CHAR_INFO v3;
COORD v4;
SMALL_RECT v5;
CONSOLE_SCREEN_BUFFER_INFO v6;
if ((h = (HANDLE)GetStdHandle(0xFFFFFFF5), (unsigned int)GetConsoleScreenBufferInfo(h, &v6)))
{
v5.Right = v6.dwSize.X;
v5.Bottom = v6.dwSize.Y;
v3.Char.UnicodeChar = 32;
v4.Y = -v6.dwSize.Y;
v3.Attributes = v6.wAttributes;
v4.X = 0;
*(DWORD *)&v5.Left = 0;
ScrollConsoleScreenBufferW(h, &v5, 0, v4, &v3);
v6.dwCursorPosition = { 0 };
HANDLE v1 = GetStdHandle(0xFFFFFFF5);
SetConsoleCursorPosition(v1, v6.dwCursorPosition);
}
This is what the system("cls"); does without having to create a process to do it.
Works really well:
#include <windows.h>
void clearscreen()
{
HANDLE hOut;
COORD Position;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
Position.X = 0;
Position.Y = 0;
SetConsoleCursorPosition(hOut, Position);
}
Here is a simple way to do it:
#include <iostream>
using namespace std;
int main()
{
cout.flush(); // Flush the output stream
system("clear"); // Clear the console with the "system" function
}
I'm using windows 10 terminal.
std::system("cls"); // cls or clear
Use System::Console::Clear();
This will clear (empty) the buffer
#include <cstdlib>
void cls(){
#if defined(_WIN32) //if windows
system("cls");
#else
system("clear"); //if other
#endif //finish
}
The just call cls() anywhere
use: clrscr();
#include <iostream>
using namespace std;
int main()
{
clrscr();
cout << "Hello World!" << endl;
return 0;
}
The easiest way would be to flush the stream multiple times ( ideally larger then any possible console ) 1024*1024 is likely a size no console window could ever be.
int main(int argc, char *argv)
{
for(int i = 0; i <1024*1024; i++)
std::cout << ' ' << std::endl;
return 0;
}
The only problem with this is the software cursor; that blinking thing ( or non blinking thing ) depending on platform / console will be at the end of the console, opposed to the top of it. However this should never induce any trouble hopefully.
Related
As in the title. How can I clear console in C++?
For pure C++
You can't. C++ doesn't even have the concept of a console.
The program could be printing to a printer, outputting straight to a file, or being redirected to the input of another program for all it cares. Even if you could clear the console in C++, it would make those cases significantly messier.
See this entry in the comp.lang.c++ FAQ:
https://isocpp.org/wiki/faq/input-output#clear-screen
OS-Specific
If it still makes sense to clear the console in your program, and you are interested in operating system specific solutions, those do exist.
For Windows (as in your tag), check out this link:
How do we clear the console in assembly?
Edit: This answer previously mentioned using system("cls");, because Microsoft said to do that. However it has been pointed out in the comments that this is not a safe thing to do. I have removed the link to the Microsoft article because of this problem.
Libraries (somewhat portable)
ncurses is a library that supports console manipulation:
http://www.gnu.org/software/ncurses/ (runs on Posix systems)
http://gnuwin32.sourceforge.net/packages/ncurses.htm (somewhat old Windows port)
For Windows, via Console API:
void clear() {
COORD topLeft = { 0, 0 };
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen;
DWORD written;
GetConsoleScreenBufferInfo(console, &screen);
FillConsoleOutputCharacterA(
console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
FillConsoleOutputAttribute(
console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
SetConsoleCursorPosition(console, topLeft);
}
It happily ignores all possible errors, but hey, it's console clearing. Not like system("cls") handles errors any better.
For *nixes, you usually can go with ANSI escape codes, so it'd be:
void clear() {
// CSI[2J clears screen, CSI[H moves the cursor to top-left corner
std::cout << "\x1B[2J\x1B[H";
}
Using system for this is just ugly.
The easiest way for me without having to reinvent the wheel.
void Clear()
{
#if defined _WIN32
system("cls");
//clrscr(); // including header file : conio.h
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
system("clear");
//std::cout<< u8"\033[2J\033[1;1H"; //Using ANSI Escape Sequences
#elif defined (__APPLE__)
system("clear");
#endif
}
On Windows you can use "conio.h" header and call clrscr function to avoid the use of system funtion.
#include <conio.h>
clrscr();
On Linux you can use ANSI Escape sequences to avoid use of system function. Check this reference ANSI Escape Sequences
std::cout<< u8"\033[2J\033[1;1H";
On MacOS
Investigating...
For Linux/Unix and maybe some others but not for Windows before 10 TH2:
printf("\033c");
will reset terminal.
outputting multiple lines to window console is useless..it just adds empty lines to it.
sadly, way is windows specific and involves either conio.h (and clrscr() may not exist, that's not a standard header either) or Win API method
#include <windows.h>
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,
(TCHAR) ' ',
cellCount,
homeCoords,
&count
)) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,
csbi.wAttributes,
cellCount,
homeCoords,
&count
)) return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
For POSIX system it's way simpler, you may use ncurses or terminal functions
#include <unistd.h>
#include <term.h>
void ClearScreen()
{
if (!cur_term)
{
int result;
setupterm( NULL, STDOUT_FILENO, &result );
if (result <= 0) return;
}
putp( tigetstr( "clear" ) );
}
// #define _WIN32_WINNT 0x0500 // windows >= 2000
#include <windows.h>
#include <iostream>
using namespace std;
void pos(short C, short R)
{
COORD xy ;
xy.X = C ;
xy.Y = R ;
SetConsoleCursorPosition(
GetStdHandle(STD_OUTPUT_HANDLE), xy);
}
void cls( )
{
pos(0,0);
for(int j=0;j<100;j++)
cout << string(100, ' ');
pos(0,0);
}
int main( void )
{
// write somthing and wait
for(int j=0;j<100;j++)
cout << string(10, 'a');
cout << "\n\npress any key to cls... ";
cin.get();
// clean the screen
cls();
return 0;
}
To clear the screen you will first need to include the following header:
#include <stdlib.h>
this will import windows commands. Then you can use the 'system' function to run Batch commands (which edit the console). On Windows in C++, the command to clear the screen would be:
system("CLS");
And that would clear the console. The entire code would look like this:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
system("CLS");
}
And that's all you need! Goodluck :)
In Windows:
#include <cstdlib>
int main() {
std::system("cls");
return 0;
}
In Linux/Unix:
#include <cstdlib>
int main() {
std::system("clear");
return 0;
}
This is hard for to do on MAC seeing as it doesn't have access to the windows functions that can help clear the screen. My best fix is to loop and add lines until the terminal is clear and then run the program. However this isn't as efficient or memory friendly if you use this primarily and often.
void clearScreen(){
int clear = 5;
do {
cout << endl;
clear -= 1;
} while (clear !=0);
}
Use system("cls") to clear the screen:
#include <stdlib.h>
int main(void)
{
system("cls");
return 0;
}
In Windows we have multiple options :
clrscr() (Header File : conio.h)
system("cls") (Header File : stdlib.h)
In Linux, use system("clear") (Header File : stdlib.h)
If you're on Windows:
HANDLE h;
CHAR_INFO v3;
COORD v4;
SMALL_RECT v5;
CONSOLE_SCREEN_BUFFER_INFO v6;
if ((h = (HANDLE)GetStdHandle(0xFFFFFFF5), (unsigned int)GetConsoleScreenBufferInfo(h, &v6)))
{
v5.Right = v6.dwSize.X;
v5.Bottom = v6.dwSize.Y;
v3.Char.UnicodeChar = 32;
v4.Y = -v6.dwSize.Y;
v3.Attributes = v6.wAttributes;
v4.X = 0;
*(DWORD *)&v5.Left = 0;
ScrollConsoleScreenBufferW(h, &v5, 0, v4, &v3);
v6.dwCursorPosition = { 0 };
HANDLE v1 = GetStdHandle(0xFFFFFFF5);
SetConsoleCursorPosition(v1, v6.dwCursorPosition);
}
This is what the system("cls"); does without having to create a process to do it.
Works really well:
#include <windows.h>
void clearscreen()
{
HANDLE hOut;
COORD Position;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
Position.X = 0;
Position.Y = 0;
SetConsoleCursorPosition(hOut, Position);
}
Here is a simple way to do it:
#include <iostream>
using namespace std;
int main()
{
cout.flush(); // Flush the output stream
system("clear"); // Clear the console with the "system" function
}
I'm using windows 10 terminal.
std::system("cls"); // cls or clear
Use System::Console::Clear();
This will clear (empty) the buffer
#include <cstdlib>
void cls(){
#if defined(_WIN32) //if windows
system("cls");
#else
system("clear"); //if other
#endif //finish
}
The just call cls() anywhere
use: clrscr();
#include <iostream>
using namespace std;
int main()
{
clrscr();
cout << "Hello World!" << endl;
return 0;
}
The easiest way would be to flush the stream multiple times ( ideally larger then any possible console ) 1024*1024 is likely a size no console window could ever be.
int main(int argc, char *argv)
{
for(int i = 0; i <1024*1024; i++)
std::cout << ' ' << std::endl;
return 0;
}
The only problem with this is the software cursor; that blinking thing ( or non blinking thing ) depending on platform / console will be at the end of the console, opposed to the top of it. However this should never induce any trouble hopefully.
As in the title. How can I clear console in C++?
For pure C++
You can't. C++ doesn't even have the concept of a console.
The program could be printing to a printer, outputting straight to a file, or being redirected to the input of another program for all it cares. Even if you could clear the console in C++, it would make those cases significantly messier.
See this entry in the comp.lang.c++ FAQ:
https://isocpp.org/wiki/faq/input-output#clear-screen
OS-Specific
If it still makes sense to clear the console in your program, and you are interested in operating system specific solutions, those do exist.
For Windows (as in your tag), check out this link:
How do we clear the console in assembly?
Edit: This answer previously mentioned using system("cls");, because Microsoft said to do that. However it has been pointed out in the comments that this is not a safe thing to do. I have removed the link to the Microsoft article because of this problem.
Libraries (somewhat portable)
ncurses is a library that supports console manipulation:
http://www.gnu.org/software/ncurses/ (runs on Posix systems)
http://gnuwin32.sourceforge.net/packages/ncurses.htm (somewhat old Windows port)
For Windows, via Console API:
void clear() {
COORD topLeft = { 0, 0 };
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen;
DWORD written;
GetConsoleScreenBufferInfo(console, &screen);
FillConsoleOutputCharacterA(
console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
FillConsoleOutputAttribute(
console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
SetConsoleCursorPosition(console, topLeft);
}
It happily ignores all possible errors, but hey, it's console clearing. Not like system("cls") handles errors any better.
For *nixes, you usually can go with ANSI escape codes, so it'd be:
void clear() {
// CSI[2J clears screen, CSI[H moves the cursor to top-left corner
std::cout << "\x1B[2J\x1B[H";
}
Using system for this is just ugly.
The easiest way for me without having to reinvent the wheel.
void Clear()
{
#if defined _WIN32
system("cls");
//clrscr(); // including header file : conio.h
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
system("clear");
//std::cout<< u8"\033[2J\033[1;1H"; //Using ANSI Escape Sequences
#elif defined (__APPLE__)
system("clear");
#endif
}
On Windows you can use "conio.h" header and call clrscr function to avoid the use of system funtion.
#include <conio.h>
clrscr();
On Linux you can use ANSI Escape sequences to avoid use of system function. Check this reference ANSI Escape Sequences
std::cout<< u8"\033[2J\033[1;1H";
On MacOS
Investigating...
For Linux/Unix and maybe some others but not for Windows before 10 TH2:
printf("\033c");
will reset terminal.
outputting multiple lines to window console is useless..it just adds empty lines to it.
sadly, way is windows specific and involves either conio.h (and clrscr() may not exist, that's not a standard header either) or Win API method
#include <windows.h>
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,
(TCHAR) ' ',
cellCount,
homeCoords,
&count
)) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,
csbi.wAttributes,
cellCount,
homeCoords,
&count
)) return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
For POSIX system it's way simpler, you may use ncurses or terminal functions
#include <unistd.h>
#include <term.h>
void ClearScreen()
{
if (!cur_term)
{
int result;
setupterm( NULL, STDOUT_FILENO, &result );
if (result <= 0) return;
}
putp( tigetstr( "clear" ) );
}
// #define _WIN32_WINNT 0x0500 // windows >= 2000
#include <windows.h>
#include <iostream>
using namespace std;
void pos(short C, short R)
{
COORD xy ;
xy.X = C ;
xy.Y = R ;
SetConsoleCursorPosition(
GetStdHandle(STD_OUTPUT_HANDLE), xy);
}
void cls( )
{
pos(0,0);
for(int j=0;j<100;j++)
cout << string(100, ' ');
pos(0,0);
}
int main( void )
{
// write somthing and wait
for(int j=0;j<100;j++)
cout << string(10, 'a');
cout << "\n\npress any key to cls... ";
cin.get();
// clean the screen
cls();
return 0;
}
To clear the screen you will first need to include the following header:
#include <stdlib.h>
this will import windows commands. Then you can use the 'system' function to run Batch commands (which edit the console). On Windows in C++, the command to clear the screen would be:
system("CLS");
And that would clear the console. The entire code would look like this:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
system("CLS");
}
And that's all you need! Goodluck :)
In Windows:
#include <cstdlib>
int main() {
std::system("cls");
return 0;
}
In Linux/Unix:
#include <cstdlib>
int main() {
std::system("clear");
return 0;
}
This is hard for to do on MAC seeing as it doesn't have access to the windows functions that can help clear the screen. My best fix is to loop and add lines until the terminal is clear and then run the program. However this isn't as efficient or memory friendly if you use this primarily and often.
void clearScreen(){
int clear = 5;
do {
cout << endl;
clear -= 1;
} while (clear !=0);
}
Use system("cls") to clear the screen:
#include <stdlib.h>
int main(void)
{
system("cls");
return 0;
}
In Windows we have multiple options :
clrscr() (Header File : conio.h)
system("cls") (Header File : stdlib.h)
In Linux, use system("clear") (Header File : stdlib.h)
If you're on Windows:
HANDLE h;
CHAR_INFO v3;
COORD v4;
SMALL_RECT v5;
CONSOLE_SCREEN_BUFFER_INFO v6;
if ((h = (HANDLE)GetStdHandle(0xFFFFFFF5), (unsigned int)GetConsoleScreenBufferInfo(h, &v6)))
{
v5.Right = v6.dwSize.X;
v5.Bottom = v6.dwSize.Y;
v3.Char.UnicodeChar = 32;
v4.Y = -v6.dwSize.Y;
v3.Attributes = v6.wAttributes;
v4.X = 0;
*(DWORD *)&v5.Left = 0;
ScrollConsoleScreenBufferW(h, &v5, 0, v4, &v3);
v6.dwCursorPosition = { 0 };
HANDLE v1 = GetStdHandle(0xFFFFFFF5);
SetConsoleCursorPosition(v1, v6.dwCursorPosition);
}
This is what the system("cls"); does without having to create a process to do it.
Works really well:
#include <windows.h>
void clearscreen()
{
HANDLE hOut;
COORD Position;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
Position.X = 0;
Position.Y = 0;
SetConsoleCursorPosition(hOut, Position);
}
Here is a simple way to do it:
#include <iostream>
using namespace std;
int main()
{
cout.flush(); // Flush the output stream
system("clear"); // Clear the console with the "system" function
}
I'm using windows 10 terminal.
std::system("cls"); // cls or clear
Use System::Console::Clear();
This will clear (empty) the buffer
#include <cstdlib>
void cls(){
#if defined(_WIN32) //if windows
system("cls");
#else
system("clear"); //if other
#endif //finish
}
The just call cls() anywhere
use: clrscr();
#include <iostream>
using namespace std;
int main()
{
clrscr();
cout << "Hello World!" << endl;
return 0;
}
The easiest way would be to flush the stream multiple times ( ideally larger then any possible console ) 1024*1024 is likely a size no console window could ever be.
int main(int argc, char *argv)
{
for(int i = 0; i <1024*1024; i++)
std::cout << ' ' << std::endl;
return 0;
}
The only problem with this is the software cursor; that blinking thing ( or non blinking thing ) depending on platform / console will be at the end of the console, opposed to the top of it. However this should never induce any trouble hopefully.
I am creating a console application in C. This is a game in which characters are falling down and user has to press that specific key on the keyboard. I don't know how to detect which key is pressed by the user without pausing the falling characters. When I use scanf the Program waits for input and everything pauses.
Please help me soon!
There is a function called kbhit() or _kbhit it is in the <conio.h> library it returns true or false depending whether a key was hit. So you can go with something like this:
while (1){
if ( _kbhit() )
key_code = _getch();
// do stuff depending on key_code
else
continue;
Also use getch() or _getch which reads a character directly from the console and not from the buffer. You can read more about conio.h functions here they might be very useful for what you want to do.
Note: conio.h is not a standard library and implementations may vary from compiler to compiler.
You may probably look for ncurses
ncurses (new curses) is a programming library that provides an API
which allows the programmer to write text-based user interfaces in a
terminal-independent manner. It is a toolkit for developing "GUI-like"
application software that runs under a terminal emulator.
Also check C/C++: Capture characters from standard input without waiting for enter to be pressed
#include <conio.h>
if (kbhit()!=0) {
cout<<getch()<<endl;
}
I think this might be the non-blocking keyboard input you are looking for.
void simple_keyboard_input() //win32 & conio.h
{
if (kbhit())
{
KB_code = getch();
//cout<<"KB_code = "<<KB_code<<"\n";
switch (KB_code)
{
case KB_ESCAPE:
QuitGame=true;
break;
}//switch
}//if kb
}//void
And as for the characters falling down.. here you go.
Code for if you are on Windows:
/* The Matrix falling numbers */
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
using namespace std;
#define KB_UP 72
#define KB_DOWN 80
#define KB_LEFT 75
#define KB_RIGHT 77
#define KB_ESCAPE 27
#define KB_F8 66
/* Variables*/
char screen_buffer[2000]={' '};
int y_coord[2000]={0};
int x=0, y=0,dy=0;
int XMAX=77;
int YMAX=23;
int KB_code=0;
bool QuitGame=false;
int platformX=35, platformY=23;
/* function prototypes*/
void gotoxy(int x, int y);
void clrscr(void);
void setcolor(WORD color);
void simple_keyboard_input();
void draw_falling_numbers();
void draw_platform();
/* main */
int main(void)
{
/* generate random seed */
srand ( time(NULL) );
/* generate random number*/
for(int i=0;i<XMAX;i++) y_coord[i]= rand() % YMAX;
while(!QuitGame)
{
/* simple keyboard input */
simple_keyboard_input();
/* draw falling numbers */
draw_falling_numbers();
}
/* restore text color */
setcolor(7);
clrscr( );
cout<<" \n";
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
/* functions */
void draw_falling_numbers()
{
for(x=0;x<=XMAX;x++)
{
/* generate random number */
int MatixNumber=rand() % 2 ;
/* update falling number */
y_coord[x]=y_coord[x]+1;
if (y_coord[x]>YMAX) y_coord[x]=0;
/* draw dark color */
setcolor(2);
gotoxy(x ,y_coord[x]-1); cout<<" "<<MatixNumber<<" ";
/* draw light color */
setcolor(10);
gotoxy(x ,y_coord[x]); cout<<" "<<MatixNumber<<" ";
}
/* wait some milliseconds */
Sleep(50);
//clrscr( );
}
void draw_platform()
{
setcolor(7);
gotoxy(platformX ,platformY);cout<<" ";
gotoxy(platformX ,platformY);cout<<"ÜÜÜÜÜÜ";
setcolor(7);
Sleep(5);
}
void simple_keyboard_input()
{
if (kbhit())
{
KB_code = getch();
//cout<<"KB_code = "<<KB_code<<"\n";
switch (KB_code)
{
case KB_ESCAPE:
QuitGame=true;
break;
case KB_LEFT:
//Do something
platformX=platformX-4;if(platformX<3) platformX=3;
break;
case KB_RIGHT:
//Do something
platformX=platformX+4;if(platformX>74) platformX=74;
break;
case KB_UP:
//Do something
break;
case KB_DOWN:
//Do something
break;
}
}
}
void setcolor(WORD color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color);
return;
}
void gotoxy(int x, int y)
{
static HANDLE hStdout = NULL;
COORD coord;
coord.X = x;
coord.Y = y;
if(!hStdout)
{
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
}
SetConsoleCursorPosition(hStdout,coord);
}
void clrscr(void)
{
static HANDLE hStdout = NULL;
static CONSOLE_SCREEN_BUFFER_INFO csbi;
const COORD startCoords = {0,0};
DWORD dummy;
if(!hStdout)
{
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdout,&csbi);
}
FillConsoleOutputCharacter(hStdout,
' ',
csbi.dwSize.X * csbi.dwSize.Y,
startCoords,
&dummy);
gotoxy(0,0);
}
I want to have user press the space key to jump out of the while loop.
For example:
while ( some condition )
{
printf ("Press space bar to continue...");
}
Thanks!!
I think you mean the following as long as a spacebar followed by the enter key is acceptable given your comments above.
char input = 0;
while( input != ' ' )
{
printf("Press space bar to continue...\n");
scanf("%c",&input);
}
Or if you prefer, without hitting the enter key:
#include <stdio.h>
int main(int argc, char **argv)
{
char input = 0;
while( input != ' ' )
{
printf("Press space bar to continue...\n");
input = getch();
}
}
This worked on my msysgit bash shell. BUT, some people will insist that it work on Linux as well. Which is fine I guess, I love Linux, but I said the above solution worked on msysgit. The following works on my, let me be specific, Oracle VM for Ubuntu 10.10.
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
int main(int argc, char **argv)
{
char input = 0;
while( input != ' ' )
{
printf("Press space bar to continue...\n");
input = mygetch();
}
}
int mygetch(void)
{
struct termios oldt, newt;
int ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
The mygetch came from here.
Capturing keystrokes under most platforms requires you to access the console directly. Typically there are libraries available to help you with that. Low-level libraries are termcap (which is derived from terminal capabilities) libraries. There is a "portable" layer on top of termcap called curses. Linux uses the GNU version which is called ncurses and is actually available on a multitude of platforms.
Curses is extensively documented, you can start a tutorial using
$ man ncurses
Your problem requires steps to initialize the console and set up keystroke reader. There are several ways to achieve your desired effect.
I am posting a working example for you to play with. It shows some basic ideas in curses:
/* file: curses_ex1.c */
#include <stdio.h>
#include <curses.h>
const char rotary[4] = "/-\\|";
int main() {
WINDOW *w;
int i = 0;
w = initscr();
if ( w == NULL ) {
return -1; /* unable to initialize curses */
}
timeout(500); /* do not block */
mvprintw(0, 0, "Press space bar to break out of the loop.");
noecho();
for(i = 0; ; i++) { /* no condition so loops forever */
int c;
mvaddch(0, 42, rotary[i%4]); /* display rotator */
c = getch(); /* get a character */
if ( c == ' ')
break;
if ( c != ERR ) { /* not a space but another valid key */
mvprintw(1, 0, "You need to press a space for me to stop (you pressed `%c')", c);
}
}
endwin();
return 0;
}
To compile it:
cc -o curses_ex1 curses_ex1.c -lcurses
Make a variable x = 1, put that in the condition, when they press space bar, set x to 2.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Colorize stdout output to Windows cmd.exe from console C++ app
I am using codeblocks on Windows XP and I need a way to output colored text, and maybe change the color of the background as well in a console application.
I tried the conio.h functions but they don't seem to be compatible with code blocks.
It looks like you'll want to use some Windows API features to accomplish this.
If you were using Cygwin for windows, it'd be a bit easier.
Here's an example courtesy of daniweb:
// color your text in Windows console mode
// colors are 0=black 1=blue 2=green and so on to 15=white
// colorattribute = foreground + background * 16
// to get red text on yellow use 4 + 14*16 = 228
// light red on yellow would be 12 + 14*16 = 236
// a Dev-C++ tested console application by vegaseat 07nov2004
#include <iostream>
#include <windows.h> // WinApi header
using namespace std; // std::cout, std::cin
int main()
{
HANDLE hConsole;
int k;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// you can loop k higher to see more color choices
for(k = 1; k < 255; k++)
{
// pick the colorattribute k you want
SetConsoleTextAttribute(hConsole, k);
cout << k << " I want to be nice today!" << endl;
}
cin.get(); // wait
return 0;
}
This piece of code might help:
WinConsole.h
#pragma once
typedef void* HANDLE;
class WinConsole
{
public:
WinConsole(void);
~WinConsole(void);
void SetColour(WORD colour);
WORD GetDefaultColour() const;
void Reset();
private:
HANDLE fConsoleHandle;
CONSOLE_SCREEN_BUFFER_INFO fDefaultScreenBufferInfo;
};
WinConsole.cpp
#include "WinConsole.h"
#define WIN32_LEAN_AND_MEAN
#define <Windows.h>
WinConsole::WinConsole(void)
{
fConsoleHandle = ::GetStdHandle(STD_OUTPUT_HANDLE);
if (INVALID_HANDLE_VALUE != fConsoleHandle)
{
::GetConsoleScreenBufferInfo(fConsoleHandle, &fDefaultScreenBufferInfo);
}
}
WinConsole::~WinConsole(void)
{
}
void WinConsole::SetColour( WORD colour )
{
if (INVALID_HANDLE_VALUE != fConsoleHandle)
{
::CONSOLE_SCREEN_BUFFER_INFO info = { sizeof(CONSOLE_SCREEN_BUFFER_INFO), 0 };
if(::GetConsoleScreenBufferInfo(fConsoleHandle, &info))
{
::SetConsoleTextAttribute(fConsoleHandle, (info.wAttributes & 0xff00)|colour);
}
}
}
void WinConsole::Reset()
{
if (INVALID_HANDLE_VALUE != fConsoleHandle)
{
::SetConsoleTextAttribute(fConsoleHandle, fDefaultScreenBufferInfo.wAttributes);
}
}
WORD WinConsole::GetDefaultColour() const
{
if (INVALID_HANDLE_VALUE != fConsoleHandle)
{
return (WORD)(fDefaultScreenBufferInfo.wAttributes & 0x00ff);
}
return e_FGRed | e_FGGreen | e_FGBlue;
}
Usage:
WinConsole console;
console.SetColour(FOREGROUND_RED|BACKGROUND_BLUE); // Superman style ;)