c++ - 更新控制台 C++ 上打印的值

标签 c++ windows c++14

我如何更新 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/

相关文章:

windows - "fuser -k <folder>"的 Windows 批处理等价物是什么?

c++ - 使用新对象重新分配 `unique_ptr` 值的便捷类型推断方法

c++ - 是否可以创建自己的 Qt 注释?

windows - 从 Windows 命令行获取文件夹大小

python - 如何安装 pyCurl?

c++ - 推断模板参数对象成员的类型

c++ - 返回多个值中最小值的 min() 的简洁实现

c++ - 主题名称的 MacAddress - Arduino IDE MQTT

c++ - 我怎样才能让 Doxygen 不记录我的 include guard?

c++ - OpenCV C++ 从矩形区域设置 ROI