C - 获取输入类型枚举

Mat*_*ias 6 c int char

是否可以scanf定义数据类型?

#include <stdio.h>
enum numberByMonth {jan=1,feb,mar,apr,may,jun,jul,aug,sep,okt,nov,dec};
main(){
printf("\n");
printf("Get Number By Month (type first 3 letters): ");
enum numberByMonth stringy;
scanf("%u",stringy);
printf("Your month number is: %u",stringy);
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我扫描哪种数据类型?我把它设置为%u因为gcc告诉我它是无符号整数.

wog*_*gio 5

你写的代码应该可以工作,但不是你想要的方式,事实上 enum 在编译后作为整数受到威胁,并且在你的 "jan,feb,mar,apr,may,jun,jul, aug,sep,okt,nov,dec",因此您的程序仅使用 scanf 从命令行解析一个无符号数,并在 printf 之后返回相同的数。您可能想要这个

#include <stdio.h>
#include <string.h>
char* months[] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","okt","nov","dec"};

int main()
{
    printf("\n");
    printf("Get Number By Month (type first 3 letters): ");
    char str[3];
    scanf("%s",str);
    int i;
    for(i=0; i<12; i++)
    {
        if(!strcmp(str,months[i]))
        {
            printf("Your month number is: %d",i+1);
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它不使用枚举,但这是合理的,因为枚举用于在不影响效率的情况下保持源代码的可读性,因此作为整数而不是字符串受到威胁,因此如果您想做的是字符串解析,则必须使用字符串,因为您必须将用户输入与“jan”、“feb”等进行比较。