Clear Screen Command in C++ - c++

I want to clear the screen after user enters some numbers in C++. I'm programming in console application mode.
so how to do it? My OS is win7 and My IDE is CodeBlocks and the Compiler is MingW...

It depends of your OS,
If you use linux:
system("clear");
If you use windows:
system("cls");
but this make your application lees portable, it's preferable to do
cout << string(50, '\n');
this line will print lines to seem like the terminal was 'cleared'.
A good article about that problem:
http://www.cplusplus.com/articles/4z18T05o/

You can use the clrscr() defined in conio.h.
Ways to clear screen the output screen.

you can try system methods E.g. system("CLS");

link the conio.h in your compiler. I forgot how to do that. if you will use clear screen repeatedly put this function.
enter code here
void clrscr()
{
system("cls");
}

That's what Microsoft has to say about clearing a console:
#include <windows.h>
void cls( HANDLE hConsole )
{
COORD coordScreen = { 0, 0 }; // home for the cursor
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD dwConSize;
// Get the number of character cells in the current buffer.
if( !GetConsoleScreenBufferInfo( hConsole, &csbi ))
{
return;
}
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
// Fill the entire screen with blanks.
if( !FillConsoleOutputCharacter( hConsole, // Handle to console screen buffer
(TCHAR) ' ', // Character to write to the buffer
dwConSize, // Number of cells to write
coordScreen, // Coordinates of first cell
&cCharsWritten ))// Receive number of characters written
{
return;
}
// Get the current text attribute.
if( !GetConsoleScreenBufferInfo( hConsole, &csbi ))
{
return;
}
// Set the buffer's attributes accordingly.
if( !FillConsoleOutputAttribute( hConsole, // Handle to console screen buffer
csbi.wAttributes, // Character attributes to use
dwConSize, // Number of cells to set attribute
coordScreen, // Coordinates of first cell
&cCharsWritten )) // Receive number of characters written
{
return;
}
// Put the cursor at its home coordinates.
SetConsoleCursorPosition( hConsole, coordScreen );
}
int main()
{
HANDLE hStdout;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
cls(hStdout);
return 0;
}

system("cls");
Brilliant. So what happens if I replace the Windows cls with my own malicious cls? You've just given me control, thanks! This is what's called a back door, and you left it wide open by using an insecure technique.
Source: http://www.daniweb.com/software-development/cpp/threads/76934/how-do-i-clear-my-screen-in-c.

One method is to output '\f' (corresponding to the ASCII form feed character, code 12, which is used by line printers to eject a page, and recognized by some common terminals and emulators as a clear screen).
That won't work on Windows.
#ifdef _WIN32
/* windows hack */
#else
std::cout << '\f' std::flush;
#endif

Related

'Specific' Double buffering with this code?

For this code I am trying to implement double buffering so that it does not blink when updating the std::cout on my console window in windows 10. What is the best way to implement this into my current code? I am looking at some Microsoft documentation but I can't figure out a way to merge it so to speak?
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
homeCoords.X = 0;
homeCoords.Y = 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);
}
The basic idea is to call CreateConsoleScreenBuffer to create an off-screen buffer. Then clear/fill it as needed by passing the handle to that screen buffer when you do your calls to FillConsoleOutputCharacter, FillConsoleOutputAttribute, etc. When it's ready for the user to view, call SetConsoleActiveScreenBuffer to make it the active buffer for the console.
Note that in most cases you won't want to create a new screen buffer every time you clear the screen--rather you'll probably want to create two screen buffers when you start your program, and alternate between the two as you write and display output.

ShowCursor(FALSE) does not hide cursor on console application

I know this may sound to be a duplicate question but trust me it's not.
I have referred this question, but was not of much help as I am trying with a console application and the answerer himself tells he does not know the reason why ShowCursor(FALSE) does not work for console applications.
This thread did not help me either.
Here are the things I tried:
Using ShowCursor():
while(ShowCursor(false)>=0); //did not work
I first suspected that it was because of this statement in the msdn :
When Windows starts up, it checks if you have a mouse. If so, then the cursor show count is initialized to zero; otherwise, it is initialized to negative one.
I thought maybe in the latest windows, it doesn't recognize the connected mouse or the trackpad as an installed mouse and maybe that's why it didn't work. The following code shows it is not the case:
void UsingShowCursor()
{
CURSORINFO info;
info.cbSize = sizeof(CURSORINFO);
cout << ShowCursor(FALSE);
cout << ShowCursor(FALSE);
cout << ShowCursor(FALSE);
GetCursorInfo( &info ); //info.flags is CURSOR_SHOWING
}
Because I get -1, -2, -3. That means the initial show cursor count is obviously 0 and it does identify the installed mouse.
And another thing to note is that the GetCursorInfo() also tells that the cursor is showing.
Using SetCursor()
void UsingSetCursor()
{
HCURSOR prev = SetCursor(NULL);
int i = 0;
while(i++<10)
{
cout<<i<<endl;
Sleep(1000);
}
if( SetCursor(prev) == NULL ) //check if the previos cursor was NULL
cout<<"cursor was hidden and shown after 10 secs\n";
}
Doesn't work either.
This also did not work:
SetCursor(LoadCursor(NULL, NULL));
Edit:
Using LoadImage
Did not work either.
void UsingLoadImage()
{
// Save a copy of the default cursor
HANDLE arrowHandle = LoadImage(NULL, MAKEINTRESOURCE(IDC_ARROW), IMAGE_CURSOR, 0, 0, LR_SHARED);
HCURSOR hcArrow = CopyCursor(arrowHandle);
HCURSOR noCursorHandle = (HCURSOR)LoadImage(NULL, IDC_ARROW, IMAGE_CURSOR,1,1,LR_SHARED); //a single pixel thick cursor so that it wont be visible
HCURSOR noCursor = CopyCursor(noCursorHandle);
SetSystemCursor(noCursor, OCR_NORMAL);
int i =0 ;
while(i++<10)
{
cout<<i<<endl;
Sleep(1000);
}
//revert to previous cursor
SetSystemCursor(hcArrow, OCR_NORMAL);
DestroyCursor(hcArrow);
}
What can be the mistake? How can we hide the mouse for a console application?
You can use LoadImage() to achieve what you want. Here is the modified working version of the function UsingLoadImage() you quoted in the question. You have to include a cursor resource file to your visual studio project. Download the cursor from here or create your own.
Resource Files->Add->Existng Item and browse to the nocursor.cur file.
void UsingLoadImage()
{
// Save a copy of the default cursor
HANDLE arrowHandle = LoadImage(NULL, MAKEINTRESOURCE(IDC_ARROW), IMAGE_CURSOR, 0, 0, LR_SHARED);
HCURSOR hcArrow = CopyCursor(arrowHandle);
// Set the cursor to a transparent one to emulate no cursor
HANDLE noCursorHandle = LoadImage(GetModuleHandle(NULL), L"nocursor.cur", IMAGE_CURSOR, 0, 0, LR_LOADFROMFILE); //worked
//HANDLE noCursorHandle = LoadCursorFromFile(L"nocursor.cur"); //this also worked
HCURSOR noCursor = CopyCursor(noCursorHandle);
SetSystemCursor(noCursor, OCR_NORMAL);
int i =0 ;
while(i++<10)
{
cout<<i<<endl;
Sleep(1000);
}
SetSystemCursor(hcArrow, OCR_NORMAL);
DestroyCursor(hcArrow);
}
This would replace the normal arrow cursor with the transparent one. If you want to hide all the other cursor like the text, loading, hand cursors etc you have to hide them individually. If you don't want that to be the case, then you should opt out of the console application as many commenters have pointed out.
Hope this helps.

XCode windows.h and Displaying Colored Text

In html5, you can do make colored text by doing this:
.foo
{
color: rgb(0,0,0);
}
I have recently started c++, and would like to display colored text to the user. I've Googled this and came up with stuff like this:
http://www.cplusplus.com/forum/beginner/5830/
Duoas' code snippet (shown below) looked interesting and I tried to run it on XCode.
#include <iostream>
#include <windows.h>
int main()
{
const WORD colors[] =
{
0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F,
0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6
};
HANDLE hstdin = GetStdHandle( STD_INPUT_HANDLE );
HANDLE hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
WORD index = 0;
// Remember how things were when we started
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo( hstdout, &csbi );
// Tell the user how to stop
SetConsoleTextAttribute( hstdout, 0xEC );
std::cout << "Press any key to quit.\n";
// Draw pretty colors until the user presses any key
while (WaitForSingleObject( hstdin, 100 ) == WAIT_TIMEOUT)
{
SetConsoleTextAttribute( hstdout, colors[ index ] );
std::cout << "\t\t\t\t Hello World \t\t\t\t" << std::endl;
if (++index > sizeof(colors)/sizeof(colors[0]))
index = 0;
}
FlushConsoleInputBuffer( hstdin );
// Keep users happy
SetConsoleTextAttribute( hstdout, csbi.wAttributes );
return 0;
}
However, the error I get is
2:21: fatal error: windows.h: No such file or directory
compilation terminated.
So here's my question:
Is there an alternative to windows.h in XCode?
If not, how can you display colors to the console?
(note: I am trying to make my hello world program display hello world in another color, rather than black)
Any help is appreciated.
Thanks!
EDIT:
Ok, thanks to duskwuff's answer, I know windows.h can only be run on windows. I have a PC, but it's not running on the compiler I am currently using. What compiler can I use to run the code sample?
The sample code you are trying to use is highly specific to the Windows console, and has no direct equivalent in macOS.
The Xcode console does not support colors.
If you are running your application in the macOS Terminal (not the Xcode console), you can use ncurses to display colors. Alternatively, you can use color code escapes directly.

In Windows, Does SetCurrentConsoleFontEx change console's font size?

Other guys recommend the SetCurrentConsoleFontEx function but I don't know how to apply it to my project.
I want to change the font size of only some texts, not all texts.
Does SetCurrentConsoleFontEx() change the console's font size?
Or are there other ways to change it?
If there is, please show me the console function and a simple example.
Here is an example of using SetCurrentConsoleFontEx to change the console's font size. This affects the entire console window -- so like Joachim Pileborg already said, if you want mixed font sizes in a single console window, this won't help you.
#define _WIN32_WINNT 0x500
#include <Windows.h>
// PrintChars sends ASCII characters to console output
// for demonstration purposes.
// depends only on Win32 API
static void PrintChars() {
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD num_written;
static const char* cr_lf = "\r\n";
for(char c=' '; c<'\x7f'; ++c) {
WriteFile(hStdout, &c, 1, &num_written, NULL);
if(c % 16 == 15) WriteFile(hStdout, cr_lf, 2, &num_written, NULL);
}
WriteFile(hStdout, cr_lf, 2, &num_written, NULL);
}
// WaitEnter blocks execution until the user
// presses the enter key.
// depends only on Win32 API
static void WaitEnter() {
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
char buffer;
DWORD num_read;
do {
num_read = 0;
ReadFile(hStdin, &buffer, 1, &num_read, NULL);
} while(num_read && buffer != '\n');
}
int main() {
// Display some example characters
PrintChars();
// Wait for the user to see how the current font looks
WaitEnter();
// Get a handle to the current console screen buffer
HANDLE hcsb = CreateFileA("CONOUT$", GENERIC_WRITE | GENERIC_READ,
FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
CONSOLE_FONT_INFOEX cfi = {sizeof(cfi)};
// Populate cfi with the screen buffer's current font info
GetCurrentConsoleFontEx(hcsb, FALSE, &cfi);
// Modify the font size in cfi
cfi.dwFontSize.X *= 2;
cfi.dwFontSize.Y *= 2;
// Use cfi to set the screen buffer's new font
SetCurrentConsoleFontEx(hcsb, FALSE, &cfi);
// Wait for the user to see the difference before exiting
WaitEnter();
CloseHandle(hcsb);
}

Allegro 5 & C++ - Creating a fullscreen console?

All right, here's my main goal: get a fullscreen, non-windowed console program (that looks like the DOS operating system when you open it). I've defined ALLEGRO_USE_CONSOLE and all that stuff. Here's my full code to look at:
#define _WIN32_WINNT 0x0500
#define ALLEGRO_USE_CONSOLE
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include "include/allegro.h"
using namespace std;
void SetColor(unsigned short hColor) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), hColor);
}
void Dots() {
int i = 1;
while (i <= 3) {
cout << ".";
Sleep(750);
i++;
}
}
void ClearConsoleScreen() {
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
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 );
}
int main() {
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_DISPLAY_MODE disp_data;
al_init(); // I'm not checking the return value for simplicity.
al_get_display_mode(al_get_num_display_modes() - 1, &disp_data);
al_set_new_display_flags(ALLEGRO_FULLSCREEN);
display = al_create_display(disp_data.width, disp_data.height);
al_rest(3);
al_destroy_display(display);
}
So what exactly do I need to do to be able to make the console full screen (non-windowed & borderless) AND be able to use cout and such? I'm running Win7 as well.
ALLEGRO_USE_CONSOLE just tells Allegro that you're planning on running the program with with a console window; you still have to set the subsystem to "console" in your linker options. Allegro has nothing to do with creating the console window.
Now, if you just want to make the console fullscreen on windows, there's SetConsoleDisplayMode but that has nothing to do with Allegro. You can't use Allegro's drawing API because there's no Direct3D or OpenGL context to use.
Edit: It seems the above function no longer works on modern versions of windows...
Using a console is extremely platform specific, which is part of the reason why allegro_native_dialog exists. But there's no way to put that into a fullscreen mode.
If you want cross-platform functionality, you could create your own emulated console using Allegro's drawing API, but it would be a large undertaking.
Generally people who want a console application don't care exactly how it looks, only that the right data comes out for the data that you put in.