Frank Hamill
Frank Hamill

Reputation: 1

locating an element in a string and comparing it in C

I'm having trouble with what I think is a segfault when I attempt to access a specific element of a string. Specifically, I'm trying to determine the letter at the end of 'longitude' and check whether it's a 'W' or not. However, I end up crashing before I even get to the strcmp part. Here's the code:

int main{
    int Val;
    char longitude[20] = "081-28-23.2590W";
    char direction = longitude[14];         //pretty sure it's crashing on this line

    printf("%s\n", direction);              //this does not print

    Val = strcmp(direction, "W");           //And I think this is right, but not sure
    if(Val==0)
    { DO STUFF;}
    else{DO MORE STUFF}
}

Also, I'm not even sure if the strcmp part is correct, as the program crashes before it gets there. What am I doing wrong?

Upvotes: 0

Views: 39

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

I'm trying to determine the letter at the end of 'longitude'

char longitude[20] = "081-28-23.2590W";
//...
size_t n = strlen( longitude ); 
char direction = n == 0 ? '\0' : longitude[n-1];

// ...
printf("%c\n", direction);              
       ^^^        

and check whether it's a 'W' or not

if ( toupper( ( unsigned char )direction ) == 'W' )
{
    //...
}
else
{
    //...
}

Upvotes: 0

John3136
John3136

Reputation: 29266

printf("%s\n", direction); Is the problem.

direction is a single character while %s tells printf to expect a 0 terminated string.

Also, standard naming convention would be val not Val, and perhaps something more like isEast (since strcmp returns 0/false for 'W'). I assume you have got the correct main() { ... } - your question has it wrong. You should just cut and paste the real code so people don't address the red herrings.

As @Kaylum points out, I missed the same problem in strcmp which compares 2 strings not one character and one string. In this case you can just say isWest = (direction == 'W'); instead of using strcmp.

For the sake of completeness you could leave it all "as is" by saying char *direction = &longitude[14]; now direction is a 0 terminated string and so printf and strcmp work. I would suggest this is not a good solution...

Upvotes: 2

Related Questions