using namespace std; int main() { char ch1 = 'A'; char ch2 = 'B'; char ch3 = '\n'...">

Why is the letter "D" missing from the output?

#include <iostream> using namespace std; int main() { char ch1 = 'A'; char ch2 = 'B'; char ch3 = '\n'; cout << ch1 << '\t' << ch2 << ch3; cout << 'C' << '\t' << 'D' << '\b' << ch1 << ch3; //return 0; system("pause"); } 

Exit:

 AB CA 

Why is the last letter A, not D?

+5
source share
8 answers

You will get everything you cout . It’s just that the terminal interprets '\b' as "go back one character" . Try redirecting the output to a file and examine it using the (hexadecimal) editor to see that all characters (including '\b' ) are there.

At first glance, you might think that the terminals print the output as it is. This is not true. Terminals change the way they behave when they encounter one of the terminal’s special escape sequences or characters. The symbol '\b' (= 0x08 = backspace) is one of them. More details can be found at http://ascii-table.com/ansi-escape-sequences.php . You can try to print some of them on the terminal and see how it changes colors, rewrite the current lines, etc. Etc. In fact, you can use these special sequences and characters to create complete graphical applications on the command line.

Note, however, that not with all programs, you can rely on the "redirect to a file" trick to find out which terminal escape sequences they write to stdout. Many programs detect whether they record a terminal or not, and accordingly adjust their use (or lack thereof) of terminal control sequences.

+14
source

\b is the backspace, so you move the cursor one position to the left, and then overwrite D with ch1 , which contains A

+11
source
 cout << ch1 << '\t' << ch2 << ch3; 

prints A , tab B , and then a newline.

 cout << 'C' << '\t' << 'D' << '\b' << ch1 << ch3; 

displays the C tab D , then moves the cursor beyond D , prints A (this overwrites the D character), and then prints a newline character.

\b escape sequence that represents the backspace . It moves the cursor one step back.

+6
source

Others explained why D overwrites A , because \b is an escape sequence for backspace.

I would like to add that on different machines the output may be different. How \b actually displayed, it depends on the terminal implementation.

+2
source

Why is the last letter A, not D?

Since the last visible character you output is A :

 cout << 'C' << '\t' << 'D' << '\b' << ch1 << ch3; 

ch1 - A , ch3 - a new line. And D not displayed because you deleted it with '\b'

+1
source

What does this line do cout << 'C' << '\t' << 'D' << '\b' << ch1 << ch3; :

Seal C,

Make a space (tab \ t)

Seal D

Go back (backspace \b )

Seal A, where D (D is now erased)

New line (\ n)

+1
source

Because \ b bounces back and overwrites D

0
source

Because of this line in the code // 'D' <'\ b' <ch1 <, 'D' prints D '\ b' - this is backspace, so D erased ch1 prints a value equal to A

0
source

All Articles