Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print to console without flooding in C++

Tags:

c++

printf

My apologies for an inaccurate title, but I'm not sure what this is called exactly.

How would one print to the console a single, updating line?

For example, if I wanted to print a percent completion status every cycle but not flood the console with steams of text, how would I accomplish this? (What is this called? -- for future Googling)

Thank you!

like image 518
Derek Avatar asked Sep 02 '09 00:09

Derek


3 Answers

Curses is only way to do this portably.

Have a look at this: http://code.google.com/p/tinycurses/wiki/basic1

like image 34
Martin York Avatar answered Nov 03 '22 09:11

Martin York


There is no portable way to clean the screen though there is a simple way to return to the beginning of the line using \r then overwriting what we wrote before. I am using Sleep from Windows API:

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
 for(int i = 1; i <= 10; i++)
 {
  std::cout << i*10 << '%';
  std::cout.flush(); // see wintermute's comment
  Sleep(1000);
  std::cout << '\r';
 }
}
like image 141
Khaled Alshaya Avatar answered Nov 03 '22 09:11

Khaled Alshaya


The basic solution is to:

loop:
    backspace (over written text)
    write (without newline)
    flush
    wait and get updates

Alternatively, you could try a solution using the curses library - though I'm not sure whether this is quite what you're after. Curses provides your basic ascii graphics for text based GUIs (sometimes called a TUI).

like image 2
PinkTriangles Avatar answered Nov 03 '22 09:11

PinkTriangles