2

在下面的程序中,我试图改进在linux C++ 控制台应用程序GetCharAt中返回给定位置的字符SetCursorPosition并将终端光标移动到给定位置的函数。但是每个功能都会相互干扰。例如,注释掉将带回.mainSetCursorPositionGetCharAt

#include <streambuf>
#include <iostream>
using namespace std;
#include <stdio.h>

string console_string;

struct capturebuf : public streambuf
{
    streambuf* d_sbuf;

public:
    capturebuf():
        d_sbuf(cout.rdbuf())

    {
        cout.rdbuf(this);
    }
    ~capturebuf()
    {
        cout.rdbuf(this -> d_sbuf);
    }
    int overflow(int c)
    {
        if (c != char_traits<char>::eof())
        {
            console_string.push_back(c);
        }
        return this -> d_sbuf->sputc(c);
    }
    int sync()
    {
        return this -> d_sbuf->pubsync();
    }
} console_string_activator;

char GetCharAt(short x, short y)
{
    if(x < 1)
        x = 1;
    if(y < 1)
        y = 1;

    bool falg = false;
    unsigned i;
    for(i = 0; 1 < y; i++)
    {
        if(i >=  console_string.size())
            return 0;
        if(console_string[i] == '\n')
            y--;
    }
    unsigned j;
    for(j = 0; console_string[i + j] != '\n' && j < x; j++)
    {
        if(i + j >= console_string.size())
            return 0;
    }
    if(i + j - 1 < console_string.size())
        return console_string[i + j - 1];
    return 0;
}

void SetCursorPosition(short x,short y)
{
    char buffer1[33] = {0};
    char buffer2[33] = {0};

    string a = "\e[";

    sprintf(buffer1,"%i",y);
    sprintf(buffer2,"%i",x);

    string xx = buffer1;
    string yy = buffer2;

    cout<< a + xx + ";" + yy + "f";
    cout.flush();
}

void SetCursorPosition2(short x, short y)
{
    printf("\e[%i;%if",x,y);
    cout.flush();
}

int main()
{
    SetCursorPosition(1,1); // comment out this line for normal functionality
    cout << "hello" "\n";

    for(unsigned j = 1; j <= 5; j++)
    {
        printf("%c",GetCharAt(j,1));
    }
    cout<< "\n";
}

我怎样才能改变SetCursorPosition它不会干扰GetCharAt

4

1 回答 1

1

The approach you're trying here is so fragile as to be impossible. GetCharAt() assumes that every character that's output is printable, and that nothing is moving the cursor around. Your SetCursorPosition() does exactly that, so the idea of tracking what has been output so far simply will not work.

Plus, other processes may output stuff to the console right in the middle of your program, like a wall message from root. What you want instead is "ncurses", http://en.wikipedia.org/wiki/Ncurses, a library that probably already exists on your system. It has solved these problems already in a terminal-independent way, and provides a large suite of functions for moving around the screen, scrolling, drawing, colors, etc, all in the terminal.

于 2013-09-05T20:20:30.037 回答