我怎样才能更新C ++中的控制台打印的值
例如:_
打印的价值:10
现在我可以更新打印的价值?
我做了这样的事情:
void CursorXY(int x, int y) { COORD coords = { x, y }; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coords); } int main() { int x = 0; cout << "Value: " << x << endl; cout << "Some any value!" << endl; gotoXY(7, 0); cin >> x; gotoXY(0, 2); GetMessage(NULL, NULL, 0, 0); return 0; }
我的问题是,如果有更可怕的forms? 谢谢。
我可能会定义一个存储它自己的位置和值的field
类。 更新该值时,会适当地更新显示:
template <class T> class field { int x; int y; int w; T value; public: field(int x, int y, w = 0, T value = 0) : x(x), y(y), w(w), value(value) { redraw(); } field &operator=(T const &new_val) { value = new_val; redraw(); } voi redraw() { gotoXY(x,y); std::cout << std::string(' ', w)); gotoXY(x, y); std::cout << std::setw(w) << value; } std::istream &operator>>(std::istream &is, field &f) { is >> f.value; redraw(); return is; } };
然后我们可以使用这样的东西:
field<int> x(7, 0); std::cout << "Please enter a number: "; std::cin >> x;
使用你的gotoxy()
函数,但把它放在一个循环,使其跳回,然后更新。
就像下面的代码
#include <windows.h> #include <iostream> using namespace std; void gotoxy(int x, int y); void setcolor(WORD color); void setForeGroundAndBackGroundColor(int ForeGroundColor,int BackGroundColor); void clrscr(); int main(){ int x = 0; while(true){ gotoxy(7, 1); cout << "Value: " << x << " "<< endl; cout << "Some any value! " << endl; cin >> x; gotoxy(1, 2); } return 0; } void setcolor(WORD color){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color); return; } void setForeGroundAndBackGroundColor(int ForeGroundColor,int BackGroundColor){ int color=16*BackGroundColor+ForeGroundColor; setcolor(color); } void gotoxy(int x, int y){ COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); return; } void clrscr(){ COORD coordScreen = { 0, 0 }; DWORD cCharsWritten; CONSOLE_SCREEN_BUFFER_INFO csbi; DWORD dwConSize; HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hConsole, &csbi); dwConSize = csbi.dwSize.X * csbi.dwSize.Y; FillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten); GetConsoleScreenBufferInfo(hConsole, &csbi); FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten); SetConsoleCursorPosition(hConsole, coordScreen); return; }