如何在命令窗口的一个位置编写变量并在同一位置更新其值

How can I write a variable in one place of command window and update its value at the same place?

本文关键字:位置 变量 更新 窗口 命令 一个      更新时间:2023-10-16

例如输出为 a=20 我想将数字"20"更改为另一个数字,并将结果写入第一个输出的同一位置,而不是在新行中(不需要最早数量的"a",只是最后一个结果很重要)我尽量避免这样的事情:

输出:

a=20
a=21
a=70
.
.
.

你试过这个吗:

printf("ra=%d",a);
// r=carriage return, returns the cursor to the beginning of current line

从形式上讲,通用解决方案需要类似 ncurses .实际上,如果您正在寻找的只是有这样的行:

a = xxx

其中xxx是一个不断发展的值,您可以输出行没有'n'(或std::flush而不是std::endl);要更新,只需输出足够的b字符即可返回到数。 像这样:

std::cout << "label = 000" << std::flush;
while ( ... ) {
    //  ...
    if ( timeToUpdate ) {
        std::cout << "bbb" << std::setw(3) << number << std::flush;
    }
}

这假设固定宽度格式(在我的示例中,没有值大于 999)。 对于可变宽度,您可以先格式化为std::ostringstream,为了确定退格数下次你必须输出。 我会使用特殊的计数器类型为此:

class DisplayedCounter
{
    int myBackslashCount;
    int myCurrentValue;
public:
    DisplayedCounter()
        : myBackslashCount(0)
        , myCurrentValue(0)
    {
    }
    //  Functions to evolve the current value...
    //  Could be no more than an operator=( int )
    friend std::ostream& operator<<(
        std::ostream& dest,
        DisplayedCounter const& source )
    {
        dest << std::string( myBackslashCount, 'b' );
        std::ostringstream tmp;
        tmp << myCurrentValue;
        myBackslashCount = tmp.str().size();
        dest << tmp.str() << std::flush();
        return dest;
    }
};

上一次我不得不这样做(当恐龙在地球上漫游,牛仔布很酷的时候),我们使用了诅咒。

您可以存储所需的所有输出,并在每次更改值时重新绘制整个控制台窗口。在Linux上不知道,但在Windows上,您可以使用以下内容清除控制台:

system("cls");