#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");
}
Output is:
A B
C A
Why is the last letter A and not D?
Everything you cout
gets outputted. It's just that a terminal will interpret '\b'
as "go back one character"
. Try redirecting the output to a file and examine it with a (hex)editor to see that all the characters (including '\b'
) are there.
At a first glance, one might think that terminals print output as-is. That's incorrect, though. Terminals change the way they behave whenever they encounter one of special terminal control sequences or characters. The '\b'
(=0x08
=backspace) character is one of those. More can be found at http://ascii-table.com/ansi-escape-sequences.php . You can try printing some of those to a terminal and see it change colors, rewrite current lines and so on and so forth. In fact, you can use these special sequences and characters to make complete GUI-like apps in the command-line.
Note however, that not with all programs you can rely on the "redirect to a file"
trick to see what terminal control sequences they write to stdout. Many programs detect whether they're writing to a terminal or not and adjust their usage (or lack thereof) of terminal control sequences accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With