to lexicographically compare kth word from two strings

  c++, function, return-value

I m trying to write a c++ function to lexicographically compare kth word from two strings. here is my function :

bool kth_lexo ()
{
    int k = 2 ;
    str1 = "123 300 60009" ;
    str2 = "1500 10002" ;

// to store the kth word of fist string in ptr1
    char *ptr1 = strtok( (char*)str1.c_str() ," "); 
    for(int i = 1; i<k; i++)
    {
        ptr1 = strtok(NULL," ");
    }

// to store the kth word of second string in ptr2
    char *ptr2 = strtok( (char*)str2.c_str() ," "); 
    for(int i = 1; i<k; i++)
    {
        ptr2 = strtok(NULL," ");
    }

    string st1 = ptr1 ;
    string st2 = ptr2 ;
    return st1 > st2 ;


} 

In this function my lexicographical comparison works fine, as this func returns 1 because 300 (2nd word of str1) is lexicographically bigger than 10002 (2nd word of str2)

My Problem :
If i slightly modify my function by replacing last line of previous function by this return ptr1>ptr2 ;

now my new function lokks something like this :

bool kth_lexo ()
{
    int k = 2 ;
    str1 = "123 300 60009" ;
    str2 = "1500 10002" ;

// to store the kth word of fist string in ptr1
    char *ptr1 = strtok( (char*)str1.c_str() ," "); 
    for(int i = 1; i<k; i++)
    {
        ptr1 = strtok(NULL," ");
    }

// to store the kth word of second string in ptr2
    char *ptr2 = strtok( (char*)str2.c_str() ," "); 
    for(int i = 1; i<k; i++)
    {
        ptr2 = strtok(NULL," ");
    }

// modified line compared to previous function
    return ptr1 > ptr2 ;


}

for this modified function each time my output consistently comes out to be 0, no matter whether kth word of str1 stored in ptr1 is lexicographically greater or smaller than kth word of str2 stored in ptr2.

also even after modifying the return statement by this line doesn’t bring much help :
return (*ptr1)>(*ptr2) ;

So what’s the problem with either of these two return statement lines in my modified function for comparing the kth word of both the strings:

return ptr1 > ptr2 ;

OR

return (*ptr1) > (*ptr2) ;

Source: Windows Questions C++

LEAVE A COMMENT