Is there a "proper" way to clear the console window in C, besides using system("cls")?
printf("\e[1;1H\e[2J");
This function will work on ANSI terminals, demands POSIX. I assume there is a version that might also work on window's console, since it also supports ANSI escape sequences.
#include <unistd.h>
void clearScreen()
{
const char *CLEAR_SCREEN_ANSI = "\e[1;1H\e[2J";
write(STDOUT_FILENO, CLEAR_SCREEN_ANSI, 12);
}
There are some other
alternatives, some of which don't move the cursor to {1,1}.
Well, C doesn't understand the concept of screen. So any code would fail to be portable. Maybe take a look at conio.h or
curses, according to your needs?
Portability is an issue, no matter what library is used.
For portability, try this:
#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("\e[1;1H\e[2J")
#endif
Then simply call clrscr(). On Windows, it will use conio.h's clrscr(), and on Linux, it will use ANSI escape codes.
If you really want to do it "properly", you can eliminate the middlemen (conio, printf, etc.) and do it with just the low-level system tools (prepare for a massive code-dump):
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#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 );
}
#else // !_WIN32
#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" ) );
}
#endif
A workaround tested on Windows(cmd.exe), Linux(Bash and zsh) and OS X(zsh):
#include <stdlib.h>
void clrscr()
{
system("#cls||clear");
}
Using macros you can check if you're on Windows, Linux, Mac or Unix, and call the respective function depending on the current platform. Something as follows:
void clear(){
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
system("clear");
#endif
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
}
Since you mention cls, it sounds like you are referring to windows. If so, then this KB item has the code that will do it. I just tried it, and it worked when I called it with the following code:
cls( GetStdHandle( STD_OUTPUT_HANDLE ));
#include <conio.h>
and use
clrscr()
There is no C portable way to do this. Although various cursor manipulation libraries like curses are relatively portable. conio.h is portable between OS/2 DOS and Windows, but not to *nix variants.
The entire notion of a "console" is a concept outside of the scope of standard C.
If you are looking for a pure Win32 API solution, There is no single call in the Windows console API to do this. One way is to FillConsoleOutputCharacter of a sufficiently large number of characters. Or WriteConsoleOutput You can use GetConsoleScreenBufferInfo to find out how many characters will be enough.
You can also create an entirely new Console Screen Buffer and make the current one.
Windows:
system("cls");
Unix:
system("clear");
You could instead, insert newline chars until everything gets scrolled, take a look here.
With that, you achieve portability easily.
just type clrscr(); function in void main().
as example:
void main()
{
clrscr();
printf("Hello m fresher in programming c.");
getch();
}
clrscr();
function easy to clear screen.
In Windows I have made the mistake of using
system("clear")
but that is actually for Linux
The Windows type is
system("cls")
without #include conio.h
The proper way to do it is by using tput or terminfo functions to obtain terminal properties and then insert newlines according to the dimensions..
Just call this function below:
void clearScreen() {
system("clear");
}
This should work. Then just call cls(); whenever you want to clear the screen.
(using the method suggested before.)
#include <stdio.h>
void cls()
{
int x;
for ( x = 0; x < 10; x++ )
{
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Related
I want to know: how to clean screen on an UNIX-based system? I searched on the Internet, but I've just found how to do it on Windows: system("CLS")
I don't want exactly to clean cpmpletely the screen, but I want to open a "new page", such as in the NANO and VI editors. Thanks
Maybe you can make use of escape codes
#include <stdio.h>
#define clear() printf("\033[H\033[J")
int main(void)
{
clear();
return 0;
}
But keep in mind that this method is not compatible with all terminals
You can use the following code which use termcap for clear screen.
(don't forget to link with the library)
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
void clear_screen()
{
char buf[1024];
char *str;
tgetent(buf, getenv("TERM"));
str = tgetstr("cl", NULL);
fputs(str, stdout);
}
#include <stdlib.h>
int main(void)
{
system("clear");
}
Portable UNIX code should be using the terminfo database for all cursor and screen manipulation. This is what libraries like curses uses to achieve its effects like windowing and so forth.
The terminfo database maintains a list of capabailities (like clear which is what you would use to clear the screen and send the cursor to the top). It maintains such capabilities for a wide range of devices so that you don't have to worry about whether you're using a Linux console or a (very dated) VT52 terminal.
As to how you get the character streams for certain operations, you can choose the time-honored but rather horrible method of just using system to do it:
system ("tput clear");
Or you can capture the output of that command to a buffer so later use involve only outputting the characters rather than re-running the command:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static char scrTxtCls[20]; static size_t scrSzCls;
// Do this once.
FILE *fp = popen ("tput clear", "r");
scrSzCls = fread (scrTxtCls, 1, sizeof(scrTxtCls), fp);
pclose (fp);
if (scrSzCls == sizeof(scrTxtCls)) {
actIntelligently ("you may want to increase buffer size");
}
// Do this whenever you want to clear the screen.
write (1, cls, clssz);
Or, you can link with ncurses and use its API to get whatever capabilities you want, though this might drag in quite a bit of stuff for something as simple as clearing the screen. Still, it's an option to be considered seriously since it gives you a lot more flexibility.
It is usually not a matter of just clearing the screen, but of making a terminal aware application.
You should use the ncurses library and read the NCURSES programming HowTo
(You could perhaps use some ANSI escape codes as David RF answered, but I don't think it is a good idea)
You can achieve this using CSI sequences:
#include <stdio.h>
int main()
{
printf("\x1b[H\x1b[J");
}
What does \x1b[H?
Actually it is the same as \x1b[1;1;H, it means that it will move the cursor to row 1 and column 1.
What does \x1b[J a.k.a \x1b[0;J?
If n is 0 or missing, it will clear from cursor to end of screen.
Source: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences
Just use #include<stdlib.h> after #include<stdio.h>.
Then you can use the command system("clear");after main() {
i.e:
#include<stdio.h>
#include<stdlib.h>
int main()
{
system("clear");
After these commands you can continue with your program.
Hope this helps :)
To clear the screen using termcaps, use this :
write(1, tgetstr("cl", 0), strlen(tgetstr("cl", 0)));
Use system("clear"); with header #include <stdlib.h> (for C Language) or #include <cstdlib> (for C++).
This code is for clear screen with reset scrollbar position in terminal style windows
#include <iostream>
int main(){
std::cout << "\033c";
return 0;
}
I read that command prompt has added support for ansi escape sequences. However, when I tried to run a program that was working fine on a linux terminal it did not color properly in cmd.
#include <stdio.h>
#define ANSI_BLUE "\x1b[32m"
#define ANSI_DEF "\x1b[0m"
int main() {
printf(ANSI_BLUE "Test" ANSI_DEF);
return 0;
}
But the output I recieve when I gcc and run the exe is:
[32mTest[0m
Is this a problem with the code, compiler or cmd?
How ansi escapes are handled are terminal dependent, and since cmd is your current terminal, that what decides what to do with those escapes.
Basically, what happens when you call printf, it just sends bytes to stdout. The terminal reads stdout and decides what to do with it.
The problem here has absolutely nothing to do with the compiler. If it is your code or cmd depends on how you view things. If you're using a HP printer with a Dell printer driver, is the problem with the printer or the driver? None of them. They just don't match.
Obviously, your terminal cannot handle those escapes, so if you want to print with color, you'll have to find another way.
These questions might be relevant:
colorful text using printf in C
C color text in terminal applications in windows
So what you can do on Windows is this:
#include <windows.h>
#include <stdio.h>
// Some old MinGW/CYGWIN distributions don't define this:
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
static HANDLE stdoutHandle;
static DWORD outModeInit;
void setupConsole(void) {
DWORD outMode = 0;
stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if(stdoutHandle == INVALID_HANDLE_VALUE) {
exit(GetLastError());
}
if(!GetConsoleMode(stdoutHandle, &outMode)) {
exit(GetLastError());
}
outModeInit = outMode;
// Enable ANSI escape codes
outMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if(!SetConsoleMode(stdoutHandle, outMode)) {
exit(GetLastError());
}
}
void restoreConsole(void) {
// Reset colors
printf("\x1b[0m");
// Reset console mode
if(!SetConsoleMode(stdoutHandle, outModeInit)) {
exit(GetLastError());
}
}
int main(void) {
setupConsole();
puts("\x1b[31m\x1b[44mHello, World");
restoreConsole();
}
I also found this link about wrappers to be able to use ANSI escapes in Windows:
https://solarianprogrammer.com/2019/04/08/c-programming-ansi-escape-codes-windows-macos-linux-terminals/
As far as I know, there is no portable way of printing with colors in C.
I am writing a C program which takes user input. The user input requires some special characters which I want the reserve special keys on the keyboard for.
To keep it simple, suppose I want any occurrence of the symbol \ to be replaced with λ. So that if the user types \x.x, they see λx.x.
To clarify, I don't want their input to be repeated back to them with \ replaced by λ, I want them to enter \ but see λ immediately in the console.
Is there an easy way to do this?
Edit: Since it seems something like this is OS specific, I'd like a unix/linux solution.
I think this is a great question with many applications! For this, termios.h is better than curses.h in my opinion because with termios.h you can input to the terminal as you normally would, without requiring a fullscreen application like curses seems to. Also, you do not need to compile with a library (curses requires -lcurses option in your compiler). Note that this solution requires you to implement your own getch-like function. In addition, this solution is linux specific (AFAIK)
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <locale.h>
#include <wchar.h>
wint_t mygetwch()
{
// Save the current terminal details
struct termios echo_allowed;
tcgetattr(STDIN_FILENO, &echo_allowed);
/* Change the terminal to disallow echoing - we don't
want to see anything that we don't explicitly allow. */
struct termios echo_disallowed = echo_allowed;
echo_disallowed.c_lflag &= ~(ICANON|ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &echo_disallowed);
// Get a wide character from keyboard
wint_t wc = getwchar();
// Allow echoing again
tcsetattr(STDIN_FILENO, TCSANOW, &echo_allowed);
// Return the captured character
return wc;
}
int main()
{
// Imbue the locale so unicode has a chance to work correctly
setlocale(LC_ALL, "");
// Start endless loop to capture keyboard input
while (1) {
wint_t wc = mygetwch(); // get a wide character from stdin
if (wc==WEOF) // exit if that character is WEOF
break;
else if (wc==L'\\') // replace all instances of \ with λ
wprintf(L"%lc",L'λ');
else // otherwise just print the character
wprintf(L"%lc",wc);
}
return 0;
}
Is there an easy way to do this?
Yes, it's easy with a readline macro mapping \ to λ. Demo program:
/* cc -lreadline */
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
main()
{
// bind the backslash key to lambda's UTF-8 code 0xCE 0xBB (cebb)
rl_parse_and_bind((char []){"\"\\\\\":'\xCE\xBB'"});
unsigned char *line, *cp;
while (cp = line = readline("? "))
{
while (*cp) printf("%3x", *cp++); puts("");
free(line);
}
}
Of course a UTF-8 enabled terminal is needed for the display of λ.
#include <stdio.h>
#include <cstdlib>
rec();
main()
{
int a, fact;
char q, n, y;
printf("\nEnter any number ");
scanf("%d", & a);
fact = rec(a);
printf("Factorial value = %d\n", fact);
printf("do you want to exit.....(y/n):");
scanf("%s" ,&q);
if (q == 'n')
{
system("cls");
main();
}
else
return 0;
}
rec(int x)
{
int f;
if (x == 1)
return 1;
else
f = x * rec(x - 1);
return f;
}
I'm using code blocks but I don't know how to clear the screen. I searched then found system("cls"); within header file #include<cstdlib>, but it shows the error cstdlib: no such file of directory. What should I do ?
Change
#include <cstdlib>
to
#include <stdlib.h>
cstdlib is a C++ header file, and thus will be unusable in C.
Clearing the screen is outside the purview of a normal C program. It depends on the operating system.
For windows, you should look into conio.
For unix, look into curses or termios.
system() always launches a sub-shell which may or may not have any effect on the environment of the parent program. You do need a system-call, but not a system() call.
I didn't always know this. I once (long ago) suggested in comp.lang.c that someone should try system("exit"); to close the window around the DOS program. But that, of course, cannot work. And I was quickly advised to test my code before posting. :)
you have lots of problems in your code....
but for the specific problem, try #include <stdlib.h>
use the #include<stdlib.h> that's where the clear screen function is defined.
To use system("cls") you need the header <iostream>. This will allow all system() types to execute. Unsure if it is a C++ header file, but it works for the compiler that I use.
They asked how to capture keys such as F11 or insand getchr does not return anything for those keys, and there is nothing I can find working that accepts raw input from input events..
I am now trying ncurses/curses in a C++ program to capture these keys.
My program to test is simple, it is basically:
#include <stdlib.h>
#include <stdio.h>
#include <curses.h>
int main() {
int car;
while(c != '\b') {
c = getch();
printf("%i", c);
}
return 0;
}
I use it of course the same as another getch() function, but it returns -1 infinite times.. I am using a recent kernel in Arch linux, in a standard terminal (tested in xterm as well)
Is there a certain switch I need to switch on in order to use this getch() in the libraries?
You need to call initscr(); to initialise curses before calling getch().
In addition, you probably want non-line-buffered mode, so you should also call cbreak(); noecho(); (echo mode should not be used with cbreak mode).