C/Data Type/Enum
Содержание
Define and use enum
#include <stdio.h>
enum computer {keyboard, CPU, screen, printer, mouse};
int main(void)
{
enum computer comp;
comp = CPU;
printf("%d", comp);
return 0;
}
Map enum to char and output with for loop
#include <stdio.h>
enum spectrum { red, orange, yellow} colour;
char *rainbow[] = { "red", "orange", "yellow" };
int main() {
for ( colour = red; colour <= yellow; colour++ ) {
printf ( "%s ", rainbow[colour]);
}
printf ( "\n" );
}
Map enum to char array
#include <stdio.h>
enum status{
one,
two,
three,
four,
five
};
char *stats[] = {
"1",
"2",
"3",
"4",
"5"
};
#define NUMBER_OF_INPUTS ( sizeof ( stats ) / sizeof ( stats[0]))
int main() {
enum status;
int name;
printf ( "Number of Inputs is: %d\n", NUMBER_OF_INPUTS );
for ( name = one; name < NUMBER_OF_INPUTS; name++) {
printf ( "\n%s", stats[ name ] );
}
printf ( "\n\n" );
}
Map enum to string array
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
enum transport {car, train, airplane, bus} tp;
char trans[][20] = {
"car", "train", "airplane", "bus"
};
int main(void)
{
printf("Press a key to select transport: ");
/* Generate a new random number */
while(!kbhit())
rand();
getch(); /* read and discard character */
tp = rand() % 4;
printf("%s", trans[tp]);
return 0;
}
Reference enum value by int
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
enum transport {car, train, airplane, bus} tp;
int main(void)
{
printf("Press a key to select transport: ");
/* generate a new random number */
while(!kbhit())
rand();
getch(); /* read and discard character */
tp = rand() % 4;
switch(tp) {
case car: printf("car");
break;
case train: printf("train");
break;
case airplane: printf("airplane");
break;
case bus: printf("bus");
}
return 0;
}