C - 获取输入类型枚举

标签 c char integer

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

#include <stdio.h>
enum numberByMonth {jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,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);
}

有人可以帮我确定应该扫描哪种数据类型吗?我将它设置为 %u,因为 gcc 告诉我它是一个无符号整数。

最佳答案

您编写的代码应该可以工作,但不是您想要的方式,事实上,枚举在编译后被视为整数,并且在您的目标文件中没有任何痕迹 “jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec”,出于这个原因,你的程序只是用 scanf 从命令行解析一个无符号数,并在 printf 之后返回相同的数字。你可能想要这个

#include <stdio.h>
#include <string.h>
char* months[] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","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;
}

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

关于C - 获取输入类型枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20177964/

相关文章:

java - 是什么导致我的代码中出现 StackoverFlowError?

c - 解析特定数字

pointers - 声明 const 指针为 int 吗?

c - 人们使用Pic和c进行计数器

c - 我正在尝试向每个新行添加数字

c - cpu怎么知道内存中的数据是数据还是命令呢? (C 编程)

c - 使用 gcc 理解共享库

C++ 读入一行字符串作为整数?

java - 将索引处的所有字符(在 StringBuilder 中)替换为另一个字符串

char - 在ABAP中的常量字符末尾添加空格