Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Getting Input Type Enum

Tags:

c

integer

char

Is it possible to scanf a defined data type?

#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);
}

Can someone help me with which datatype I should scan for? I set it to %u because gcc told me it was an unsigned integer.

like image 934
Mathias Avatar asked Nov 24 '13 18:11

Mathias


1 Answers

The code you wrote should be working, but not in the way you intended, in fact, enum are treated as integer after compilation and remains no trace in the object file of your "jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec", for this reason your program just parses an unsigned number from command line with scanf and returns the same number after printf.. You probably wanted this

#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;
}

which doesn't use enums, but it is reasonable because enums are used to preserve source readability without impairing efficiency and for this reason are threated as integers not strings, so if what you want to do is string parsing, you have to use strings because you have to compare user input with "jan", "feb" etc..

like image 155
woggioni Avatar answered Oct 24 '22 16:10

woggioni