| |||||
Technical Support Support Resources
Product Information | C51: '\N' DOES NOT WORK IN PRINTF() STATEMENTSInformation in this article applies to:
SYMPTOMSIt appears that my \n does not work in printf() statements. When I view the output on a dumb terminal, I do not see a carriage return-line feed. For example:
printf("hello world\n");
The above statement does not appear to send the '\n'. Instead, I have to use this to make it work:
printf("hello world");
putchar(CR);
Why does this happen? What is printf doing to the '\n'? CAUSEIn most C compilers, including ours, the newline escape sequence '\n' yields an ASCII line feed character. The C escape sequence for a carriage return is '\r'. When you create C programs in what the C Standard calls a "hosted implementation" (where the programs run under an operating system), the operating system or the stdio library routines are supposed to convert the newline character to whatever it takes to actually go to the beginning of the next line, e.g., carriage return + line feed. For a "freestanding implementation" (where the programs run without any operating system), the Standard doesn't specify any requirements for library routines. It is up to the compiler vendor to decide what library routines to provide, and how each should work. All Keil compilers are freestanding implementations of C. Users of our compilers send the output from printf() to a variety of devices with different requirements for marking the end of a line. So, any method we might choose to handle '\n' would be wrong in many cases. On output, the default version of our library routine putchar() handles newline characters by outputting a carriage return and a line feed. Many projects require a user-written version of putchar(). If your project has a custom putchar() function, it may handle newline characters differently. For example, it may pass all characters through with no special-case treatment for '\n' (line feed). RESOLUTIONThere are three different ways to solve this problem:
SEE ALSOLast Reviewed: Wednesday, August 03, 2005 | ||||
| |||||