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.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With