peaceman
peaceman

Reputation: 1529

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

for example the output is a=20 I want to change the number "20" to another number and write the result at the same place of first output, not in a new line (the earliest amount of "a" is not required just the last result is important) I try to avoid something like this:

output:

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

Upvotes: 2

Views: 353

Answers (4)

James Kanze
James Kanze

Reputation: 154007

Formally, the generic solution would require something like ncurses. Practically, if all you're looking for is to have a line like:

a = xxx

Where xxx is a value which constantly evolves, you can output the line without a '\n' (or a std::flush instead of std::endl); to update, just output enough \b characters to get back to the start of the number. Something like:

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

This supposes fixed width formatting (and in my example, no values larger than 999). For variable width, you can first format into an std::ostringstream, in order to determine the number of backspaces you'll have to output next time around. I'd use a special counter type for this:

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;
    }
};

Upvotes: 4

TVOHM
TVOHM

Reputation: 2742

You could store all the outputs you need and re-draw the entire console window each time a value is changed. No idea on Linux, but on Windows you can clear the console with:

system("cls");

Upvotes: 1

Crashworks
Crashworks

Reputation: 41454

The last time I had to do this (back when dinosaurs roamed the Earth and denim was cool), we used Curses.

Upvotes: 2

Dženan
Dženan

Reputation: 3395

Have you tried this:

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

Upvotes: 6

Related Questions