tags:

views:

134

answers:

3

Hi,

The following program does not work as I intended.

#include <string.h>
#include <stdio.h>

int main()
{
    const char *c = "abcdef";

    // prints 'f' as expected
    printf("%c\n", c[5]);

    // comparison fails, does not print "yes"
    if (c[5] == 'f')
        printf("yes");
    return 0;
}

How can I compare a character in a string literal to a character value? Is it possible without using ASCII related functions i.e. chr() or ord() suppose those exist. ( I remember using them back in Pascal days)

Thanks

+5  A: 

There must be something else going on with your environment. I just threw that into gcc and it prints out "yes" as expected.

Are you sure you aren't just missing the "yes" because printf does not add a new line by default, so it could be "yes[your shell prompt]" and you're just overlooking the yes?

Matt Greer
+3  A: 

I don't see anything wrong with the code, except:

  • You should end your output with a newline. I suggest puts("yes"); (or if you want to use printf(), printf("yes\n");).
  • You don't need string.h.
  • What you are doing is better than resorting to ASCII or any other encoding. The comparison you have works for all encodings, whereas if you resort to ASCII comparison, things will break on platforms with non-ASCII encodings. The comparison, as written, is fine.

The main problem seems to be that the output isn't terminated with a newline.

Alok
A: 

When you try to access the char at index 5 using printf and get 'f'.
Now you are not modifying the string anywhere ( You cannot modify it as its a string constant).
Later you are comparing the same char at index 5 with char constant 'f'. This test should return true and the "yes" should be printed in the output.

codaddict