Printing a number, then erasing it and printing another number in its place

Viewed 69

I am making a simple roulette game, and I want to implement a roulette spinning code, so like in my terminal I would have something like this Spinning: 25 then the number after spinning will change, so it erases that 25 and then it's Spinning: 14 then Spinning: 35 and eventually it stops. All I can do is make it look like this:

Spinning: 24
Spinning: 34
Spinning: 2
Spinning: x...
etc..

basically it's just random numbers. I am just curious is this possible to get rid of this Spinning: x spamming and just make it one Spinning: x with x changing constantly in ONE place. If I used printf("Spinning: %d", rand()%36+1); then printf("Spinning: %d, rand()36%+1) it is just going to stack on each other, but I want my number changes to change only in ONE place if that makes sense.

1 Answers

On many, if not most, consoles, the \r (carriage return) character will set the cursor to the start of the current line. So, in such cases, adding that character to the beginning of your output would work:

printf("\rSpinning: %d    ", rand()%36+1);

I have also added a few spaces at the end, just in case the 'new' number is shorter than the 'old'.


On the origin of the name, "Carriage Return," Wikipedia has a good article.

Related