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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…