Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help understanding how \n, \b, and \r will render printf output

I wrote the following program in the C and when I run it, I was surprised by looking at the output.

Here is the program

int main()
{    
       printf("\nab");
       printf("\bsi");    
       printf("\rha");    
}

The output is :- hai whereas I was expecting "absiha" since \n is for new line, \b is for backspace(non erase) and \r is for carriage return. So I was expecting that curson would be at "i" character because \r has been applied but when I run it and saw the output I was totally surprised and confused. Can anyone please explain me the output?

like image 365
Ankur Trapasiya Avatar asked Feb 12 '12 21:02

Ankur Trapasiya


People also ask

What does \b do in printf?

The printf() function sends a formatted string to the standard output (the display). This string can display formatted variables and special control characters, such as new lines ('\n'), backspaces ('\b') and tabspaces ('\t'); these are listed in Table 2.1.

What is the basic difference between \n and \t?

The \n symbol means literally new line. This will go to the start of the next new line. The \t symbol means add a tab (which is usually 4 spaces but can easily be 2 or 8 depending on the context). The \r symbol is no more used that often.

How do I show in printf?

Generally, printf() function is used to print the text along with the values. If you want to print % as a string or text, you will have to use '%%'. Neither single % will print anything nor it will show any error or warning.

What is %W in printf?

%w.mi, %w.mI. Transfer integer data, w is the total width, m is the minimum number of non-blank digits. There is no difference between the lowercase and uppercase forms. The %d forms are identical to the %i forms and are provided for programmers familiar with C's printf.


2 Answers

Visit http://en.wikipedia.org/wiki/Escape_sequences_in_C

Escape Sequence Character \a Bell (speaker beeps) \b Backspace (non-erase) \f Form feed/clear screen \n New line \r Carriage Return \t Tab \v Vertical tab \\ Backslash \? Question mark \' Single quote \" Double quote \xnn Hexadecimal character code nn \onn Octal character code nn \nn Octal character code nn

like image 76
ridox Avatar answered Oct 21 '22 04:10

ridox


Let's take it one step at a time:

<new line>ab<backspace>si<carriage return>ha

First, handle the backspace. Note that even though it is "non-erase", the next character to be output would overwrite what was backspaced over:

<new line>asi<carriage return>ha

Now, a carriage return means to go back to the beginning of the line. So the "ha" overwrites the "as" in "asi:

<new line>hai

Now, the cursor is currently sitting on the i, so the next character to be output would overwrite i.

like image 26
Izkata Avatar answered Oct 21 '22 05:10

Izkata