Backspace printing?

Hello, I was just bored and wanted to do some text replacing stuff.

Here's my code:
1
2
3
4
5
6
7
8
9
10
#include <stdio.h> // printf
#include <unistd.h> // for the sleep function

int main ()
{
    printf( "Hello World!" );
    usleep(1000000); // usleep is in microseconds (10 to the -6)
    printf( "\b\b\b\b\b\bMyself!\n" ); // Backspace 6 times and print Myself!
    return 0;
}


What it's supposed to do is print "Hello World!" into my console, and wait 1 second, and then replace the "World!" with "Myself!"
Only problem is, when I execute it, it delays one second and then prints "Hello Myself!" without printing "Hello World!" preliminarily.

Is there a specific reason why this is happening, and if so, can I fix it?

Thanks in advance,
-Daniel
Hello,

on Windows this code doesn't work in the expected way, too. After changing the sleep-call to the WinAPI specific one it works!

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h> // printf
//#include <unistd.h> // for the sleep function
#include <windows.h>

int main ()
{
    printf( "Hello World!" );
    Sleep(5000); // usleep is in microseconds (10 to the -6)
    printf( "\b\b\b\b\b\bMyself!\n" ); // Backspace 6 times and print Myself!
    return 0;
}

Is there a specific reason why this is happening, and if so, can I fix it?
standard output is buffered.
It will not write to the screen till the buffer is full. You can change that by flushing the stream.
@ne555
This was my first thought, too. But it seems that the (u)sleep function doesn't halt thread execution properly. Don't know if this is a Windows issue or if I simply don't use it in the right way. I'm using the MingW compiler with the current Code::Blocks IDE.
Oh yay, thanks it works :)


1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h> // printf
#include <unistd.h> // for the sleep function
#include <iostream> // for flushing

int main ()
{
    printf( "Hello World!" );
    cout.flush();
    usleep(1000000); // usleep is in microseconds (10 to the -6)
    printf( "\b\b\b\b\b\bMyself!\n" ); // Backspace 6 times and print Myself!
    return 0;
}

thanks
the more i look at it, it seems that my terminal is not deleting characters that should be removed. For example when im doing a "reverse-i-search" the previous things i've typed just keep printing instead of being overwritten. Is there some way to reinstall the terminal only...i really don't want to have to reinstall ubuntu again.

http://www.softwaredownload1.com
Topic archived. No new replies allowed.