Reputation: 1188
I have a function to convert the first 3 letters of the month into a number (Jan = 1, Feb = 2, etc).
int convertDate(char date[3])
{
printf("%s", date);
if(date == 'Ian')
return 1;
else
if(date == 'Feb')
return 2;
else
if(date == 'Mar')
return 3;
else
if(date == 'Apr')
return 4;
else
if(date == 'Mai')
return 5;
else
if(date == 'Iun')
return 6;
else
if(date == 'Iul')
return 7;
else
if(date == 'Aug')
return 8;
else
if(date == 'Sep')
return 9;
else
if(date == 'Oct')
return 10;
else
if(date == 'Noi')
return 11;
else
if(date == 'Dec')
return 12;
else return 0;
}
But, in main() when I use:
printf("%d", convertDate("Ian"));
it returns 0 instead of 1. Same for any other month. Any suggestion?
Upvotes: 2
Views: 151
Reputation: 7349
Since in C string variables are of type char *, comparing strings like you do actually compares pointer adresses. Use strcmp()
to compare strings instead.
Also, you could use stricmp()
to do case insenstive string comparison.
Note, that you could implement your function also with a loop, defining all twelve fixed strings into an array (using strncmp() to ensure that we really only compare 3 characters)
int convertDate(char date[3])
{
const char date_names[12][4] = {
"Ian", "Feb", "Mar", /* etc. */ };
int i;
for(i = 0; i < 12; ++i)
{
if (strncmp(date_names[i], date, 3) == 0)
return i+1;
}
return 0;
}
Upvotes: 2
Reputation: 263177
That shouldn't even compile. You're comparing a char*
value (date
) to an int
value ('Ian'
).
This:
'Ian'
is not a string literal. It's a multi-character character constant, and its value is implementation-defined. It hardly ever makes sense to use it.
I'm guessing that the code you posted isn't the code you compiled. That's why you should copy-and-paste the same code that you fed to the compiler into your question.
As others have said, when comparing strings, you need to use strcmp()
, not ==
-- which means you can't use a switch
statement.
You should also be aware that the parameter declaration
char date[3]
is exactly equivalent to
char *date
The 3
is quietly ignored, and if you call dateCompare("Ianxyzfoobar")
, date
will point to a string with a length of 12.
Upvotes: 1
Reputation: 47609
You can't compare strings like that except in very specific circumstances (don't worry about that).
You should use strncmp
, "string compare". E.g.:
#include <string.h>
then
if(strncmp(date, "Ian", 3) == 0)
return 1;
Note using "
instead of '
. Using '
is entirely different, and can create a multi-byte int value on the stack, which you don't want.
Upvotes: 1
Reputation: 124632
You are performing a pointer comparison, not a string comparison. Use strcmp()
.
Upvotes: 0
Reputation: 623
You can't compare array of characters using == operator. Look at strcmp function.
Upvotes: 1
Reputation: 121961
Use strcmp()
when comparing char*
.
if (date == "Sep")
compares the base address of the char*
.
Upvotes: 5