Reputation: 339
I have a really weird problem with carriage return. I try to rewrite a line multiple times, it works fine if the line has no spaces and doesn't work if it has spaces. For instance this code
printf(" ");
printf("\rtest test");
printf(" ");
printf("\rtest test");
printf(" ");
printf("\rtest test");
printf(" ");
printf("\rtest test");
will type 4 lines "test test" while this code
printf(" ");
printf("\rtest");
printf(" ");
printf("\rtest");
printf(" ");
printf("\rtest");
printf(" ");
printf("\rtest");
will type a single line "test". What is the problem? I want to be able to rewrite any line disregard if it has spaces or not.
Upvotes: 1
Views: 2123
Reputation: 212208
\r
moves the cursor to the beginning of the physical line on the tty. If the previous print wraps the cursor to the next line (ie, the number of spaces + the number of characters in "text text" is larger than the width of the display), then the cursor is on the next physical line. You'll need to use more complex escape sequences to accomplish what you want. (ie, save/restore cursor position.) As an example (this is not portable, but works in many cases), you could do:
fputs( "\0337", stdout ); /* Save the cursor position */
printf( " ... " );
fputs( "\0338", stdout ); /* restore cursor position */
Note that if the cursor is at the bottom of the screen, this will probably not do exactly what you want. The position will be saved at the bottom of the screen, multiple lines of output will scroll, and the cursor will be restored to the bottom of the screen.
Upvotes: 8
Reputation: 93466
To print on a new line, use newline ('\n') not carriage-return.
The behaviour of '\r' on the console is to return to the start of the current line. In this case it is the large amount of space padding that was forcing a line wrap in the first instance.
In some cases a terminal can be configured to translate CR to CR+LF. Strictly '\n' is merely a LF character which moves down one line without returning to the start, but the normal behaviour for stdout is to translate that to CR+LF.
Upvotes: 0