2013-09-05 1 views
1

다음 프로그램에서는 주어진 위치에 문자를 반환하는 GetCharAt 함수와 터미널 커서를 주어진 위치로 이동시키는 SetCursorPosition 함수를 개선하려고합니다. 리눅스 C++ 콘솔 응용 프로그램. 그러나 각 기능은 다른 기능을 방해합니다. 예를 들어 main의 경우 SetCursorPosition을 주석 처리하면 GetCharAt의 일반 기능을 다시 가져옵니다.리눅스 콘솔 응용 프로그램에서 주어진 위치에 문자를 가져 오기

#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"; 
} 

가 어떻게 그것을 GetCharAt을 방해하지 않도록 SetCursorPosition을 변경할 수 있습니다 ?

답변

1

여기에서 시도하는 방식은 너무 약해서 불가능합니다. GetCharAt()은 출력되는 모든 문자가 인쇄 가능하다고 가정하고 커서를 움직이는 것이 아무것도 없다고 가정합니다. 귀하의 SetCursorPosition() 정확히 그렇게 않습니다, 그래서 지금까지 출력되었습니다 추적하는 아이디어가 작동하지 않습니다.

또한 다른 프로세스는 프로그램 중간에서 콘솔의 내용을 루트에서 wall과 같이 출력 할 수 있습니다. 대신에 시스템에 이미있는 라이브러리 인 "ncurses", http://en.wikipedia.org/wiki/Ncurses이 필요합니다. 그것은 이미 터미널 독립적 인 방법으로 이러한 문제를 해결했으며 터미널에서 스크롤, 그리기, 색상 등 화면 주위를 돌아 다니기위한 다양한 기능을 제공합니다.

+1

ncurses는 오픈 소스 아니 십니다. 나는 일반적인 터미널 솔루션을 찾고있다. konsole, xterm 또는 gnome과 같은 터미널의 내용에 접근하는 방법이 있어야합니다. – user2029077

+0

물론 오픈 소스입니다 : http://www.gnu.org/software/ncurses/. 그것은 일반적인 터미널 솔루션입니다. [이 페이지]에있는 – Peter

+0

(http://invisible-island.net/ncurses/ncurses.faq.html#who_claims_it) 오픈 소스가 아닙니다. btw, 내 프로그램이 향상되거나 터미널 stdout의 모든 내용을 복사 할 수 있다면 기쁠 것입니다. – user2029077

관련 문제