-3

I want to show a "printf" in the command only for 5 seconds, i do not find it online. Thank you so much if you take time to answer to an apprentice like me ! (CLION CONSOLE)

int main()
{
srand(time(NULL));
int a=0;
int b=0;
int c=0;
int d=0;
int e=0;

int ar=0;
int br=0;
int cr=0;
int dr=0;
int er=0;

a=rand()%1000+1;
b=rand()%1000+1;
c=rand()%1000+1;
d=rand()%1000+1;
e=rand()%1000+1;

printf("La suite à rentenir est :\n%d %d %d %d %d\n",a,b,c,d,e); <---- The printf I only want to show during 5 seconds  


scanf("%d",&ar);
scanf("%d",&br);
scanf("%d",&cr);
scanf("%d",&dr);
scanf("%d",&er);

if (ar==a && br==b && cr==c && dr==d && er==e)
    printf("BRAVO");
        else
            printf("TU AS PERDU");

return 0;

}

"

1 Answers1

2

In the code below 'message' is printed and then erased

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{
  printf("message"); fflush(stdout);
  sleep(5);
  printf("\r       \r"); fflush(stdout);
  return 0;
}

note that depending on what system you are using the library for sleep changes. On windows I think it is windows.h instead of unistd.h.

The key part to make it work is the escape code \r which returns the cursor to the beginning of the line. I put it in twice in the code. First so that the blank spaces cover the message. The second time so that the cursor is left at the beginning of the line ready for the next thing.

Note that normally in C things are not printed with printf until we get a newline character, which is the \n. In this program we get around this problem by using fflush(stdout) which forces everything to be printed on the screen immediately without waiting for \n. Of course, we don't want a newline here, because we want to stay on the same line so that we can return to the beginning of the line and overwrite the 'message' with blank characters.

This is the principle of how to do it.....

For your code pasted into the question...

printf("La suite à rentenir est :\n");
printf("%d %d %d %d %d",a,b,c,d,e); fflush(stdout); 
     //<---- The printf I only want to show during 5 seconds  
sleep(5);
printf("\r                    \r"); fflush(stdout);

This will mean that the number series to remember (La suite à rentenir) is only shown for five seconds.

A great suggestion in the comments by @chux is a refinement to measure the length of the text printed and then print white spaces over the length. The code is int len = printf("message"); .... printf("\r%*s\r", len, ""); With this added the example code above becomes

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{
  int len = printf("message: hello world"); fflush(stdout);
  sleep(5);
  printf("\r%*s\r", len, "");
  return 0;
}    

this refinement means that whatever the message length the right number of spaces will be printed to delete it.

tom
  • 1,303
  • 10
  • 17