Home > Software engineering >  Output several strings as a marquee separated by 9 characters
Output several strings as a marquee separated by 9 characters

Time:05-23

I've been following this post How to output a string in a marquee fashion? to output a marquee.

My problem is that I have a string composed of several strings separated by a character, in this case '-'. From string to string inside the marquee it needs to be 9 spaces of distance.

I have tried this code but the result is not the expected:

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

#ifdef _WIN32
    #include <windows.h>
#else
    #include <unistd.h>
#endif

void customSleep( int seconds )
{
    #ifdef _WIN32
        Sleep( 1000 * seconds );
    #else
        sleep( seconds );
    #endif
}

static char text[] = "STRING01-STRING02";
static char indexOfCharacterToPrint, i, currentStartPosition;
static char temp;
static char blanks;
static char imarquee;

int main() {
    while (1) {
        if (blanks == 0)
            indexOfCharacterToPrint = (currentStartPosition   imarquee) % strlen(text);
        temp = text[indexOfCharacterToPrint];
        if (temp == '-') {
            blanks  ;
            temp = ' ';
            if (blanks == 9)
                blanks = 0;
        }
        printf("%c", temp);
        i  ;
        imarquee  ;
        if (imarquee == 16)
            imarquee = 0;
        if (i == 16) {
            i = 0;
            currentStartPosition  ;
            customSleep(1);
            printf("\r");
        }
    }
}

The expected output is:

STRING01
TRING01         S
RING01         ST
ING01         STR
NG01         STRI
G01         STRIN
01         STRING
1         STRING0
         STRING02

The actual output is

STRING01        
 TRING02TRING01 
        TRING02S
ING01         ST
ING02STRNG01    
     TRING02STRI
01         STRIN
02STRING1       
  TRING02STRING0
STRING02STRING01
TRING02STRING01 
        RING02ST
ING01         ST

What I am missing?

CodePudding user response:

You have something to play with. It worked with the same size strings. Try to modify it to work with any size strings ( border cases)

#define MAX(a,b) ((a) > (b) ? (a) : (b))

void foo(char *words[], size_t distance)
{
    size_t s1len = strlen(words[0]);
    size_t s2len = strlen(words[1]);

    for(size_t index = 0; index < MAX(s1len, s2len)   1; index  )
    {
        for(size_t letter = index; letter < s1len; letter  )
        {
            if(letter < s1len) printf("%c", words[0][letter]);
            else printf(" ");
        }
        for(size_t space = 0; space < distance; space  )
            printf(" ");
        for(size_t letter = 0; letter < s2len - (s1len - index); letter  )
        {
            if(letter < s1len) printf("%c", words[1][letter]);
            else printf(" ");
        }
        printf("\n");

    }
    
}

int main(void)
{
    foo((char *[]){"123456789", "ABCDEFGHI"}, 5);
}

https://godbolt.org/z/s8ezaWYzY

  • Related