Skip to content

C++:Console

C/C++ 콘솔 프로그래밍에 대한 설명.

No echo mode

콘솔에서 사용자 입력에 대한 ECHO를 제거하는 방법으로, Windows버전은 아래와 같다.

#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

int main()
{
    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 
    DWORD mode = 0;
    GetConsoleMode(hStdin, &mode);
    SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));

    string s;
    getline(cin, s);

    cout << s << endl;
    return 0;
}

POSIX버전은 아래와 같다.

#include <iostream>
#include <string>
#include <termios.h>
#include <unistd.h>

using namespace std;

int main()
{
    termios oldt;
    tcgetattr(STDIN_FILENO, &oldt);
    termios newt = oldt;
    newt.c_lflag &= ~(ECHO | ICANON);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);

    string s;
    getline(cin, s);

    cout << s << endl;
    return 0;
}

Clear console

Windows버전은 아래와 같다.

#include <windows.h>
// ...
void clear()
{
    HANDLE handle;
    CONSOLE_SCREEN_BUFFER_INFO csbi;

    handle = GetStdHandle(STD_OUTPUT_HANDLE);
    if (handle == INVALID_HANDLE_VALUE) {
        return;
    }
    if (GetConsoleScreenBufferInfo(handle, &csbi) == FALSE) {
        // If the function fails, the return value is zero.
        return;
    }

    DWORD length = csbi.dwSize.X * csbi.dwSize.Y;
    COORD coord = { 0, 0 };
    DWORD written = 0;

    if (FillConsoleOutputCharacterA(handle, ' ', length, coord, &written) == FALSE) {
        return;
    }
    if (FillConsoleOutputAttribute(handle, csbi.wAttributes, length, coord, &written) == FALSE) {
        return;
    }
    SetConsoleCursorPosition(handle, coord);
}

Terminal Size

Windows버전은 아래와 같다.

#include <windows.h>
// ...
Size getTerminalSize()
{
    Size size;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    size.x = csbi.srWindow.Right  - csbi.srWindow.Left + 1;
    size.y = csbi.srWindow.Bottom - csbi.srWindow.Top  + 1;
    return size;
}

POSIX버전은 아래와 같다.

#include <sys/ioctl.h>
#include <err.h>
#include <fcntl.h>    /* open */
#include <stdio.h>  /* printf */
#include <unistd.h> /* close */
// ...
Size __getTerminalSize()
{
    Size size;

    int fd = open("/dev/tty", O_RDWR);
    winsize ws;

    if (fd < 0) {
        return size;
    }

    if (ioctl(fd, TIOCGWINSZ, &ws) == 0) {
        size.x = ws.ws_row;
        size.y = ws.ws_col;
    }

    close(fd);

    return size;
}

SIGINT (CTRL + C) Interrupt

Windows버전은 아래와 같다.

#include <windows.h>
BOOL CALLBACK __interrupt_callback(DWORD signal)
{
    if (signal == CTRL_C_EVENT) {
        ::NAMESPACE_WORLD::__interrupt();
    }
    return TRUE;
}
// ...
SetConsoleCtrlHandler(__interrupt_callback, TRUE);

POSIX버전은 아래와 같다.

#include <signal.h>
void __interrupt_callback(int signal)
{
    if (signal == SIGINT) {
        // TODO: Insert your code.
    }
}
// ...
signal(SIGINT, __interrupt_callback);

Console INPUT

See also

Favorite site

References


  1. Clear_the_screen_-_Cpp_Articles.pdf