cif-statementcharc-stringstolower

Please have a look at the code, clang is giving the error " incompatible pointer to integer conversion passing 'string' to parameter type 'int' "


float x;
    for (int i = 0; i < NUM_ITEMS; i++)
    {
        if (strcmp(tolower(item), tolower(menu[i].item)) == 0)
        {
            x = menu[i].price;
            break;
        }
    }

I'm trying to compare the item and menu[i].item by converting them both into lowercase


Solution

  • Before using a function always read the function description.

    The function tolower is declared the following way

    #include <ctype.h>
    int tolower(int c);
    

    As you can see it returns an object of the type int and in turn accepts integers. But it seems you are passing to the function strings (as character arrays or pointers).

    So the compiler issues the message.

    Also the function strcmp is declared like

    #include <string.h>
    int strcmp(const char *s1, const char *s2);
    

    That is it expects pointers to char as arguments.

    However in this if statement

    if (strcmp(tolower(item), tolower(menu[i].item)) == 0)
    

    instead of passing pointers to strings (to their first characters) to the function strcmp you are passing integers returned by the function tolower.

    It seems you need to write yourself a function that compares two strings characters of which are converted to the low case. For example the function can look the following way

    int str_tolower_cmp( const char *s1, const char *s2 )
    {
        unsigned char c1 = tolower( ( unsigned char )*s1 );
        unsigned char c2 = tolower( ( unsigned char )*s2 );
    
        while ( c1 &&  c1 == c2 )
        {
            c1 = tolower( ( unsigned char )*++s1 );
            c2 = tolower( ( unsigned char )*++s2 );
        }
    
        return ( c2 < c1 ) - ( c1 < c2 );
    }
    

    and then

    if ( str_tolower_cmp( item, menu[i].item ) == 0 )
    //...
    

    Otherwise if objects with the name item have type char then just write

    if ( tolower(( unsigned char )item) == tolower(( unsigned char )menu[i].item))
    

    Or if the variable item has type char and menu[i].item represents a string then you can write

    if ( tolower(( unsigned char )item) == tolower(( unsigned char )menu[i].item[0]))