【问题标题】:Using 'CLS' command in C causes screen blink在 C 中使用“CLS”命令会导致屏幕闪烁
【发布时间】:2015-09-03 12:44:51
【问题描述】:

每次我要去printf 里面的东西(带有GCC 编译器的Windows 环境)时,我都会尝试清除我的控制台。我正在使用 CygWin,我能做到的唯一方法是使用 system("cmd /c cls");。这很好用,但它会导致屏幕闪烁几分之一秒,这显然很烦人。

有没有其他清除控制台屏幕的方法?

【问题讨论】:

    标签: c cygwin cls


    【解决方案1】:

    我要做的第一件事就是停止使用cmd 来做这件事。 CygWin,假设您在 shell 中的某个地方而不是 Windows 控制台中运行,有一个“本机”选项,您可以使用以下任一选项:

    clear
    tput clear
    

    清除屏幕,而不调用外部cmd 解释器。

    因此,在 CygWin 中运行的程序中,您可以通过简单的方式清除屏幕:

    system("clear");
    

    当然,如果您不想运行任何 个外部可执行文件,您可以使用curses 达到相同的目的。例如,以下程序会为您清除屏幕(确保在编译命令末尾包含-lcurses):

    #include <curses.h>
    
    int main (void) {
        WINDOW *w = initscr();
        clear(); refresh(); sleep(2);
        endwin();
        return 0;
    }
    

    不要挂断它在退出时恢复的事实,您不会将此程序用作屏幕清除独立的东西。相反,这些语句将被合并到您自己的程序中,在 initscr()endwin() 调用之间,类似于:

    #include <curses.h>
    
    int main (void) {
        char buf[2],
             *msg = "Now is the time for all good men to come to lunch.";
        WINDOW *w = initscr();
    
        buf[1] = '\0';
        clear();
        refresh();
        while (*msg != '\0') {
            buf[0] = *msg++; addstr(buf);
            if ((buf[0] == ' ') || (buf[0] == '.')) {
                refresh();
                sleep(1);
            }
        }
    
        endwin();
        return 0;
    }
    

    此程序使用curses 清除屏幕,然后以单词大小的块输出消息。

    【讨论】:

    • 那我该怎么称呼它呢?通过清除();?这给了我一个undefined reference to clear 的错误
    • @michi clear not found 打印在控制台上并且屏幕没有得到清理。
    • @Bababarghi,你必须先让它在 shell 中运行。如果您在输入 clear 时从 bash 收到类似的错误,您可能需要安装更多的 CygWin:cygwin.com/cgi-bin2/…
    【解决方案2】:

    这个网页:

    http://man7.org/linux/man-pages/man4/console_codes.4.html

    包含用于处理终端屏幕/光标位置等的常用 ESC 序列

    这部分链接信息可能是您想要实现的。

    这些转义序列可以放置在您用来输出数据/文本的缓冲区的开头

    特别感兴趣的是 ESC [ 2 j: 擦除整个屏幕

    J   ED        Erase display (default: from cursor to end of display).
                     ESC [ 1 J: erase from start to cursor.
                     ESC [ 2 J: erase whole display.
                     ESC [ 3 J: erase whole display including scroll-back
                                buffer (since Linux 3.0).
    

    【讨论】:

      猜你喜欢
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多