0

I am having trouble with my code being new to C. I am simply trying to get this program to print the index where string[j] = "a". If I take out the if statement, the program will flawlessly print out all the index positions, but it doesn't work with the if statement. It is very simple for me to do this in other languages. How do you achieve this in C?

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

int main(int argc, char **argv) {
    char string[100] = "Smart Guy";

    for(int j = 0; j < strlen(string); j++) {
        if (string[j] == "a") {
            printf("%d %c\n", j, string[j]);
        }
    }

    return 0;
}
Fabio
  • 336
  • 3
  • 17
  • 3
    Do you get warnings when you compile? You should: `"a"` in double quotes is a string literal of type `char *`. You want a single char in single quotes: `'a'`. – M Oehm Sep 13 '17 at 18:00
  • 1
    @TravisAlexanderTerrell Good compilers will warn about such problems like `string[j] == "a"`. Save time, enable all compiler warnings. – chux - Reinstate Monica Sep 13 '17 at 21:55

1 Answers1

4

You can change

if (string[j] == "a") {
  printf("%d %c\n", j, string[j]);
}

to

if (string[j] == 'a') {
  printf("%d %c\n", j, string[j]);
}
Naman
  • 27,789
  • 26
  • 218
  • 353