Fabian Kunze
Fabian Kunze

Reputation: 93

Printf partly ignores format string when printing newline via '%c'

I observed some behavior I can't explain myself when using printf to print a character via format-string. It seems that when the character is newline ('\n'), the printf ignores everything up to (including) '%c' and just prints the remaining part.

Here is a minimal example (user input to disable optimization):

#include <stdio.h>
int main(){
  int c;    
  scanf("%d", &c); //read char by ascii id
  printf("FOO%cBAR (id %i)\n", c,c);
  return 0;
}

Entering 45 (the code for '-') results in output "FOO-BAR", but entering 13 ('\n') just prints "BAR". This happens both in gcc 6.3.1 and clang 3.9.1, on -Og and -O3 optimisation levels, on an linux.

This should not be related to output buffering if I'm not mistaken.

Is this behavior intended?

Upvotes: 1

Views: 1160

Answers (2)

Quentin Laill&#233;
Quentin Laill&#233;

Reputation: 125

From this answer :

\r is carriage return and moves the cursor back like if i will do-

printf("stackoverflow\rnine")
ninekoverflow

means it has shifted the cursor to the beginning of "stackoverflow" and overwrites the starting four characters since "nine" is four character long.

In this case,

BAR (id %i)\n

will overwrite "FOO".

Upvotes: 1

Weather Vane
Weather Vane

Reputation: 34575

That is because character 13 is "carriage return".

After that the first part of the message is over-written.

Newline is character 10.

Upvotes: 2

Related Questions