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

C++ 如何在命令窗口的一个位置写入变量并在同一位置更新其值?,c++,gcc,printing,C++,Gcc,Printing,例如,输出为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 上一次我不得不这样做(回到恐龙在地球上漫游,牛仔很酷的时候),我们使用了

例如,输出为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

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

您可以存储所有需要的输出,并在每次更改值时重新绘制整个控制台窗口。在Linux上不清楚,但在Windows上,您可以通过以下方式清除控制台:

system("cls");

从形式上讲,通用解决方案需要类似于
ncurses
的东西。 实际上,如果你想要的只是一条线,比如:

a = xxx
其中,
xxx
是一个不断变化的值,您可以输出该行 没有
'\n'
(或
std::flush
而不是
std::endl
);要更新, 只需输出足够的
\b
字符即可返回到 号码。比如:

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

std::难道一个老派的替代方案可以使用吗libcurses@Brady对我来说这很明显:你不再酷了。@R.MartinhoFernandes,至少我去年扔掉了我的降落伞裤:)好吧,谁知道那是什么?你可能应该在每次打印后冲洗它,就像这样:
printf(“\ra=%d”,a);fflush(stdout)
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;
    }
};