-3

I am trying to make a code that will make a spinning wheel using \|/-

Basically what needs to happen is the - line is printed then it will be replaced with \ then | then / and so on so it looks like its making an animated loading sign.The problem is I do not know how to do this.

Spektre
  • 49,595
  • 11
  • 110
  • 380
  • Only complication is that you need to return carriage before printing the next symbol so you can overwrite the existing output. – Mansoor Oct 26 '19 at 01:09
  • IIRC there where some function like `gotoxy` for console cursor I think in stdio or conio... there is also the possibility of using direct VGA access `B000:0000` instead if on PC but that is slightly dirty ... – Spektre Oct 26 '19 at 07:40

1 Answers1

0

Here is a little C program that can do something like this. This assumes that your terminal uses '\r' to go to the beginning of the line instead of the next one. The flush is used because sometimes output is buffered, so it won't print until it is flushed:

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

int main(void)
{
        printf("-");
        fflush(stdout); 
        sleep(1);
        printf("\r/");
        fflush(stdout);
        sleep(1);
        printf("\r|");
        fflush(stdout);
        sleep(1);
        printf("\r\\");
        fflush(stdout);
        sleep(1);
        printf("\n\n");
}

In practice you wouldn't be sleeping, you'd be doing work in between the print statements. In practice you'd probably want to run work in a different thread than the one that prints this, or you'd need to interrupt your work regularly to do the print.

See Difference between \n and \r? for an overview of the difference between '\n' and '\r'.

As an alternative, if you have a terminal that supports VT100 codes you can use a function like this to move the cursor to a particular location where you can draw and re-draw the animation:

void gotoxy(int x, int y)
{
    printf("%c[%d;%df", 27, y, x);
}

If neither of these approaches work you'll need to give more information about the system you are trying to do this on.

Nathan S.
  • 5,244
  • 3
  • 45
  • 55
  • @EthanKoehlerBryant Both of these will work when running from Terminal on the Mac, but won't necessarily work from Xcode's console. – Nathan S. Oct 30 '19 at 20:16