0

I found a problem in Codechef.Here is the question. The task was to find the most likely character from the given string. Firstly, I tried with == operator and then with strcmp() function. but in both cases, the intended output is not coming. In python it can be easily done with "in" operator but how to do this in c so that I get the required result.

#include <stdio.h>
#include <string.h>
int main(void) {
    char st[3];
    gets(st);
    puts(st);
     //scanf("%[^\n]%*c", st);
     //printf("%s\n", st);
    if (!(strcmp(st,"R B") ||strcmp(st,"R R")||strcmp(st,"R G")||strcmp(st,"B R")||strcmp(st,"G R")))
        printf("R");
     else if (!(strcmp(st,"B B") ||strcmp(st,"B G")||strcmp(st,"G B")))
        printf("B");
        else
            printf("G");
    /*if(s=="R B"||s=="R R"||s=="R G"||s=="B R"||s=="G R")
    printf("R");
    else if(s=="B B"||s=="B G"||s=="G B")
        printf("B");
    else if(s=="G G")
        printf("G");*/
    return 0;
}
drika
  • 17
  • 4
  • 1
    First of all, ***never ever*** use `gets`! It's so [dangerous](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) that it was even removed from the C langage with the C11 standard (and was obsolete long before). Use e.g. [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead. – Some programmer dude Dec 19 '21 at 17:40
  • 1
    Secondly, remember that strings in C are really called ***null-terminated** strings*. All strings must have space for the null-terminator, which means a string of three characters must have space for *four* to fit the terminator. Your array size of `3` together with the use of `gets` will lead to *undefined behavior*. – Some programmer dude Dec 19 '21 at 17:42
  • 2
    Do you know `strchr()` which does what the title asks? Or to find a substring, you can use `strstr()`. Aside: output *exactly* what the problem states. No more, no less. Should there be a newline? Should you echo the input? – Weather Vane Dec 19 '21 at 17:44
  • Thirdly, your logical conditions doesn't make sense. If the input is e.g. `"R B"` then `strcmp(st,"R B")` matches but all other will *not* match. And since a matching [`strcmp`](https://en.cppreference.com/w/c/string/byte/strcmp) call will return `0` (which is "false") then the other will return non-zero value (which will be "true"). That makes the whole expression "true" which you then negate to a "false". So you will not print `"R"`. You should use `strcmp(...) == 0 || strcmp(...) == 0 || ...`. instead. – Some programmer dude Dec 19 '21 at 17:45

0 Answers0