[Solved] Strings are not printed in accordance with the way they are allocated

[ad_1]

Errors were not detected because either the warnings of your compiler are not enabled, being ignored or need for a better compiler. This code does not allocate space for data being read.

Simplest solution: used fixed size arrays and limit user input.

#include <stdio.h>

int main(void) {
    char colorOne[80+1];
    printf("How many bands??\n");
    ...
    printf("\n\nEnter your first band color: ");
    if (1 != scanf("%80s", colorOne)) Handle_EOForIOError();
    ...
    printf("\n\nBand One: %s",colorOne);
}

A more robust solution would use fgets(). If the OS support getline(), consider that.

int main(void) {
    char colorOne[80+1+1];
    printf("How many bands??\n");
    ...
    printf("\n\nEnter your first band color: ");
    if (fgets(colorOne, sizeof colorOne, stdin) == NULL) Handle_EOForIOError();

    // Delete potential ending \n
    size_t len = strlen(colorOne);
    if (len > 0 && colorOne[len-1] == '\n') colorOne[--len] = 0;
    ...
    printf("\n\nBand One: %s",colorOne);
}

Practice defensive coding

0

[ad_2]

solved Strings are not printed in accordance with the way they are allocated