How does "\b" and "\n" work together when they are placed next to each other in printf.
For ex: Printf("\naa\b\n")

The solution is "aa".

I was wondering if anyone could explain me how/where "\n" is placed.

Does the occurence of "\n" just makes the file pointer to transfer to the next line without changing the content of the current position? If so, wouldn't "\n" be written at the end of the line? (If yes, where is it written? The answer in that case for the above example should have been just "a", coz Printf("\naa\bc") will give "ac" .)

Thanks in advance for clarifying !

Recommended Answers

All 3 Replies

'\n' is not the same than "\n", the first is a newline char the second is a string that contains '\n' and '\0'.
Same with any other escape characters you mention. Printf("\naa\b\n") is not the same than printf( "\naa\b\n" ); Printf("\naa\bc") '\n' can be used any where inside a literal string. It just help to format the printed text. At the end of the string is a common place to insert one, for obvious reasons.

Perhaps you could see better what is being done if: printf( ">\n<>a<>a<>\b<>\n<" );

sorry for the confusion. I was referring to "printf" and not "Printf", and also '\n'.
Thanks for making it clear for others.

Well, by the way, I am still not able to understand!

Let me rephrase the question!

In the below statement

the output (compiled and run on gcc and linux) will be


My doubt here is, what happens to '\n'? I mean where is it written? I thought it will be written at the 2nd a

ie. I thought the solution as
a'\n' {ofcourse '\n' wont be displayed on console. It makes it move advance to next line}

whereas it is displaying


it prints the two 'a' characters, then it backspaces to the point between the two 'a' characters that were just printed, then it prints a newline.

so the two 'a' characters remain, and the cursor is on the new line.

the backspace does not delete a previously printed character. you would have to overwrite it if you wanted that to happen. the new line just moves the cursor to the next line, it does not delete any chars or carry them along with it.

youre just printing to a terminal screen, not a word processor. try the following and you should see what i mean. printf("\naa\b \n"); unless, of course, i'm just wrong and dont know it yet.


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.