3

I have written a small C++ program to understand the use of \b. The program is given below -

#include <iostream>
using namespace std;
int main(){
    cout << "Hello World!" << "\b";
    return 0;
}

So, this program gives the desired output Hello World.This should not happen because backspace only moves cursor one space back and not delete it from the buffer.So,why ! is not printed?

Now,Consider another program-

#include <iostream>
using namespace std;
int main(){
    cout << "Hello World!" << "\b";
    cout << "\nAnother Line\n";
    return 0;
}

So, here the output is - Hello World! Another Line Why does the backspace does not work here? Newline should not flush the buffer,so ! should be deleted.What is the issue here?

Also,when i add either endl or \n after \b,in both the cases,the output is Hello World!.But,newline character does not flush the buffer whereas endl flushes the buffer.So, how the output is same in both the cases?

  • 2
    You have 2 wrong assumptions:.1. _"This should not happen because backspace only moves cursor one space back ..."_. 2. _"But,newline character does not flush the buffer ..."_ The latter is implementation dependend. – πάντα ῥεῖ Sep 28 '16 at 13:39
  • When your program exits the console probably prints a prompt that overwrites the "!". Also `cout` gets flushed when your program exits regardless. How `\b` works is nothing to do with `C++`. `C++` sends all characters you tell it to the console (or whatever else it happens to be connected to). How the console behaves depends on the console. – Galik Sep 28 '16 at 13:45
  • So @πάνταῥεῖ, can using `\n` flush the buffer? – Dishank Agrawal Sep 28 '16 at 13:50
  • You didnt flush the buffer. Better alternative here would be using printf, or consider ::std::cerr, because its flushed when you print something. – Kamila Szewczyk Sep 28 '16 at 13:52

1 Answers1

-1

I assume the output from your first program looks something like this?

$ ./hello
Hello World$ 

If so, the ! is not deleted from the buffer; it is clobbered when the shell prints the prompt.

With regard to the second program, when the buffer is flushed only influences when \b is sent to the terminal, not how it is processed. The \b is a part of the stream and a terminal happens to interpret this to mean "back up one column". If this is not clear, take a look at the actual bytes sent to stdout:

$ ./hello2 | hexdump -C
00000000  48 65 6c 6c 6f 20 57 6f  72 6c 64 21 08 0a 41 6e  |Hello World!..An|
00000010  6f 74 68 65 72 20 4c 69  6e 65 0a                 |other Line.|
0000001b

The \b is followed by the \n (08 and 0a respectively), matching what you wrote to cout in your program.

Finally, cout is flushed when the program exits so it does not matter whether you pass \n or endl in this example. In fact, \n will likely flush anyway since stdout is connected to a terminal.

Chris
  • 451
  • 2
  • 5