LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   workaround for C++ printf carriage return (https://www.linuxquestions.org/questions/programming-9/workaround-for-c-printf-carriage-return-482439/)

idc12 09-11-2006 10:37 AM

workaround for C++ printf carriage return
 
I am new to Linux and am porting a C++ program from ROM-DOS to Linux. I have managed to get everything working except the screen display (text screen only).
The programme is reading data from an external input and I want to update the screen with the latest readings. I do not want the screen to scroll (i.e. linefeed). I want to keep updating the values on the same line. In the ROM-DOS version I was able to do this by using the \r (carriage return) escape sequence. In the Linux program I don't get anything displayed when I use \r. The display appears when I change to using \n (newline) but then a new line of text is generated for every printf call which is not what I want.
Is there another way of doing this?

demon_vox 09-11-2006 11:07 AM

Hi,
I think that the problem with \r is that, by default, the stdout is not flushed until a \n is found. So, what you can do is flush the stdout manually everytime you want to update the screen so it gets display.
This is a simple example that worked on my PC:
Code:

#include <stdio.h>
#include <time.h>

int main() {
  int n;
  for(n = 0; n < 100; n++) {
    printf("\r%3d", n);
    fflush(stdout);  // This line flushes stdout inmediatly
    sleep(1);
  }
}

of course you dont need to sleep(1), thats just for demonstration.

If you want to make more advanced text interface, then you should turn into the ncurses library which lets you do fancy things in text mode.

Hope this is useful.
Cheers!

idc12 09-11-2006 12:13 PM

Excellent! That is exactly what I was looking for. Thanks very much.


All times are GMT -5. The time now is 04:33 AM.