David Ranieri
David Ranieri

Reputation: 41017

Printf with carriage return

printf("Hello%cWorld\n", '\r');

Outputs:

World

Because '\r' moves the cursor to the beginning of the line

Can I trust that all terminals have this behavior?

Upvotes: 3

Views: 5161

Answers (2)

sigflup
sigflup

Reputation: 305

lib curses will tell you the capabilities of your terminal.

Upvotes: 1

vvy
vvy

Reputation: 2073

.0x0d in ASCII encoding is '\r', in this case

printf("Hello%cWorld\n", 0x0d);

is equal to

printf("Hello\rWorld\n");

A common C programming error is to assume a particular encoding is in use when, in fact, another one holds.

However, it works on most computers as @Joachim Pileborg said.

BUT I suggest to use '\r' instead of 0x0d, for portability and the latter looks like a magic number, which makes others who read your code even yourself feel confused someday.

Upvotes: 0

Related Questions