在下面的程序中,我试图改进在linux C++ 控制台应用程序GetCharAt
中返回给定位置的字符SetCursorPosition
并将终端光标移动到给定位置的函数。但是每个功能都会相互干扰。例如,注释掉将带回.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";
}
我怎样才能改变SetCursorPosition
它不会干扰GetCharAt
?