user6759977
user6759977

Reputation:

printf() weird result in C

Here, my code gives weird results in the online geeksforgeeks compiler.

#include <stdio.h>

main()
{
        printf("\nhai\bas\rha\n");
}

output: haiasha

but I think correct output is haas.

Online compiler ink : http://code.geeksforgeeks.org/paWwuv

Why compiler give wrong output? please help me.

Upvotes: 0

Views: 256

Answers (4)

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

The "correct" output in this case is \nhai\bas\rha\n, exactly as you supplied it to printf, with \n, \b and \r standing for the corresponding special characters (or character combinations).

But how this output will look on a specific output device depends on the properties and capabilities of that device. It just so happens that the output device used (simulated) by your online compiler displays that sequence as haiasha.

It appears that your expectations are based on the behavior of a "typical" display terminal. Meanwhile, online compilers don't output anything directly to any "display". They intercept the standard output and then postprocess it for representation on a Web page. What you see is the result of that postprocessing.

Upvotes: 1

axiac
axiac

Reputation: 72395

\b is a special character. The terminals usually interpret it as "move the caret one character to the left". As a consequence the next printed character overwrites the last character printed before \b.

However, in other contexts the \b character may be interpreted in a different way. For example, in a file it is nothing but a regular byte (with value 8).

Upvotes: 0

Aif
Aif

Reputation: 11220

It is not a compiler error. I would blame your terminal. Here is my output on a debian machine:

$ make so
cc     so.c   -o so
$ ./so 

haas

To be sure the program actually emits the charcode you expect, you can pipe the output to xxd for instance.

Also, if you return nothing, your main function should be void. When no type qualifier is used (which I find ugly), int return type is assumed.

Upvotes: 1

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33283

The online compiler prints to an html page, not to a console. \b is displayed differently by a browser than by a terminal window.

If you run the code in the online compiler, then view the page source you can see that all characters you print are there.

Upvotes: 2

Related Questions