Home > Software design >  strstr not performing upto expectations
strstr not performing upto expectations

Time:01-09

i cant seem to find whats wrong with my logic that the strstr not performing upto my expectations

its a question to find prime number in a binary string, and i'm finding 10 or 11 in that string and the outcome is not what i've expected.

sorry if i've done a terrible silly mistake, i'm a noob.

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

int main(void)
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        char str[100000];
        scanf("%s", str);
        char ten[] = "10";
        char eleven[] = "11";
        int flag = 0;
        if (strstr(str, ten) == NULL)
        {
            flag = 1;
        }
        else if (strstr(str,eleven) == NULL)
        {
            flag = 1;
        }
        if (flag == 1)
        {
            printf("NO\n");
        }
        else if (flag == 0)
        {
            printf("YES\n");
        }
    }
    return 0;
}

input providing is

3 //test cases
1 //strings
111
101101

output getting

NO
NO
YES

output expecting

NO
YES
YES

CodePudding user response:

You say you want your code to output "YES" for "111". For that to happen, you must leave flag at zero. But you set flag to one if the string contains no "10" and "111" contains no "10".

CodePudding user response:

this code is working fine. i've made some adjustments, thanks to you guys.

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

int main(void)
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        char str[100000];
        scanf("%s", str);
        char ten[] = "10";
        char eleven[] = "11";
        int flag = 1;
        char *one = strstr(str, ten);
        char *two = strstr(str, eleven);
        if ((one == NULL) && (two == NULL))
        {
            flag = 0;
        }
        else
        {
            flag = 1;
        }
        if (flag == 0)
        {
            printf("NO\n");
        }
        else if (flag == 1)
        {
            printf("YES\n");
        }
    }
    return 0;
}

CodePudding user response:

The problem is with the if Statement. If '10' is not found in the first two characters, it would terminate there. Not checking for 11 also.

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

int main(void)
{
    int t;
    scanf(" %d", &t);
    while (t--)
    {
        char str[100000];
        scanf(" %s", str);
        char ten[] = "10";
        char eleven[] = "11";
        int flag = 0;
        if (strstr(str, ten) == NULL && strstr(str,eleven) == NULL)
        {
            flag = 1;
        }
        if (flag == 1)
            printf("NO\n");
        else
            printf("YES\n");
    }
    return 0;
}
  •  Tags:  
  • Related