我如何更新 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;
}
我的问题是是否有更不那么可怕的形式? 谢谢。
最佳答案
我可能会定义一个存储其自己的位置和值的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;
关于c++ - 更新控制台 C++ 上打印的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38272900/