Linux终端没有用ncurses显示任何内容

时间:2016-07-23 20:13:13

标签: c++ ncurses

我正在尝试创建一个库来简化ncurses用于显示颜色。我这样做是面向对象的,因此将来很容易处理变化。但问题是我无法使用此代码。

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

using namespace std;

class ColorWindow {
    private:
        bool canColor;
        WINDOW* container;
        int height, width, startx, starty;

    public:
        ColorWindow() {
            if(has_colors()) {
                canColor=true;
            }

            this->height = 20;
            this->width = 84;
            this->starty = (LINES - height) / 2;    /* Calculating for a center placement */
            this->startx = (COLS - width) / 2;
        }

        bool writeStringWithColor(int x, int y, const char* message) {
            if(!canColor) {
                writeString(3, 5, "Sorry, your term can't show colors.");
                return false;
            }

            init_pair(1, COLOR_RED, COLOR_BLACK);

            writeString(0, 10, "aaaaaaaaa");

            wattron(getContainer(), COLOR_PAIR(1));
            writeString(x, y, message);
            wattroff(getContainer(), COLOR_PAIR(1));
        }

        void writeString(int x, int y, const char* message) {
            mvwprintw(getContainer(), x, y, message);
        }

        WINDOW* createNewContainer() {
            this->container = newwin(height, width, starty, startx);
            wrefresh(this->container);      /* Show that box        */

            return getContainer();
        }

        WINDOW* getContainer() {
            return this->container;
        }

        void refreshContainer() {
            refresh();
            wrefresh(this->container);      /* Show that box        */
        }       
};

int main() {
    ColorWindow cw = ColorWindow();


    initscr();          /* Start curses mode        */
    cbreak();           /* Line buffering disabled, Pass on
                        * everything to me      */
    keypad(stdscr, TRUE);
    start_color();

    cw.createNewContainer();

    bool success = cw.writeStringWithColor(0, 10, "Hello everyone in color!!");
    if(!success)
        cw.writeString(0, 10, "Write with color failed :(");
    cw.refreshContainer();
    sleep(2);
    endwin();

    return 0;
}

先谢谢。

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些错误:

  • 您没有初始化canColorcontainer,因此将字段复制到cw中的main具有未定义的行为。修正:

    ColorWindow() : canColor(false), container(nullptr) {
    
  • writeStringWithColor在结尾处缺少return语句,也导致main中的未定义行为。修正:

    return true;
    

    writeStringWithColor

  • 的末尾
  • x的{​​{1}}来电中,您的ymvwprintw参数已被换掉。修正:

    writeString
  • mvwprintw(getContainer(), y, x, message); LINES仅在初始化ncurses后有效,因此您的COLSstarty值是垃圾。通过在startx中的ncurses初始化代码之后移动cw的初始化来修复:

    main

完整计划:

initscr();          /* Start curses mode        */
cbreak();           /* Line buffering disabled, Pass on
                    * everything to me      */
keypad(stdscr, TRUE);
start_color();

ColorWindow cw = ColorWindow();