Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c - Strings are not printed in accordance with the way they are allocated

In the code below my first output is coming back with my second string combined with my third.

#include <stdio.h>

int bandNumber;
char colorOne[];
char colorTwo[];
char colorThree[];

int main(void) {
    printf("How many bands??
");
    scanf("%d",&bandNumber);
    if(bandNumber == 3) {
        printf("

Enter your first band color: ");
        scanf("%s",colorOne);
        printf("

Enter your second band color: ");
        scanf("%s",colorTwo);
        printf("

Enter your third band color: ");
        scanf("%s",colorThree);
        printf("

Band One: %s",colorOne);
        printf("

Band Two: %s",colorTwo);
        printf("

Band Three: %s

",colorThree);
    }
}

Can anyone explain the errors and what I can do to correct them?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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??
");
    ...
    printf("

Enter your first band color: ");
    if (1 != scanf("%80s", colorOne)) Handle_EOForIOError();
    ...
    printf("

Band 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??
");
    ...
    printf("

Enter your first band color: ");
    if (fgets(colorOne, sizeof colorOne, stdin) == NULL) Handle_EOForIOError();

    // Delete potential ending 

    size_t len = strlen(colorOne);
    if (len > 0 && colorOne[len-1] == '
') colorOne[--len] = 0;
    ...
    printf("

Band One: %s",colorOne);
}

Practice defensive coding


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...