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

#define MAX_SRC_LEN 20
#define MAX_DUP_NUM 4

#define TO_TEXT(A) #A
#define BUILD_FORMAT(LEN) "%" TO_TEXT(LEN) "s"
#define INPUT_FORMAT BUILD_FORMAT(MAX_SRC_LEN)

char *copyStr(int n, const char *str);

static inline
void clearStdinBuf()
{
    char c;
    while((c = getchar()) != '\n' && c != EOF);
}

int main(void) {
    char srcStr[MAX_SRC_LEN + 1] = {0}; // +1 for '\0'
    char *dupStr;
    int n, ret;

    printf("using format for scanf: %s\n", INPUT_FORMAT);
    printf("enter a string(len<=%d):", MAX_SRC_LEN);
    ret = scanf(INPUT_FORMAT, srcStr);
    if (ret <= 0) {
        printf("error on scanf\n");
        return 1;
    }
    // clear extra input
    if (strlen(srcStr) == MAX_SRC_LEN) clearStdinBuf();

    printf("n(n<=4)=");
    do {
        ret = scanf("%d", &n);
        if (ret <= 0) clearStdinBuf();
        if (n > 0 && n <= 4) break;
        printf("the n must <= 4, got %d, please enter again:", n);
    } while (1);

    dupStr = copyStr(n, srcStr);
    printf("%s\n", dupStr);

    return 0;
}

char *copyStr(int n, const char *str) {
    int i, j, len = strlen(str);
    static char array[MAX_SRC_LEN * MAX_DUP_NUM + 1]; // +1 for '\0'
    for (i = 0; i < n; i++) {
        for (j = 0; j < len; j++) {
            array[len * i + j] = str[j];
        }
    }
    array[len * i] = '\0';
    return array;
}
