Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rollback lines from cout?

Tags:

c++

cout

I'm coding a task monitoring, which updates tasks' progress using cout. I'd like to display one task progress per line, therefore I have to rollback several lines of the console.

I insist on "several" because \b does the job for one line, but does not erase \n between lines.

I tried std::cout.seekp(std::cout.tellp() - str.length()); but tellp() returns -1 (failure).

like image 728
Mister Mystère Avatar asked Jul 18 '10 20:07

Mister Mystère


People also ask

Does cout auto flush?

It is an implementation detail, one that invariably depends on whether output is redirected. If it is not then flushing is automatic for the obvious reason, you expect to immediately see whatever you cout.

How do you stop cout without a new line?

The cout operator does not insert a line break at the end of the output. One way to print two lines is to use the endl manipulator, which will put in a line break. The new line character \n can be used as an alternative to endl. The backslash (\) is called an escape character and indicates a special character.

Can cout print multiple lines?

The endl statement can be used to print the multi-line string in a single cout statement.


1 Answers

You can do cout << '\r'; to jump to the beginning of the current line, but moving upwards is system-specific. For Unix, see man termcap and man terminfo (and search for cursor_up). On ANSI-compatible terminals (such as most modern terminals available on Unix), this works to move up: cout << "\e[A";.

Don't try seeking in cout, it's unseekable most of the time (except when redirected to a file).

As mentioned in other answers, using the ncurses (or slang) library provides a good abstraction for terminal I/O on Unix.

Instead of filling with spaces (which is error-prone, because not every terminal is 80 characters wide), you can do \r + clr_eol: std::cout << "\r\e[K" << std::flush.

like image 96
pts Avatar answered Oct 22 '22 04:10

pts