Question

what i intend to do is get a "protypo" string at first.Then get an "input" string and store that input string in an array of strings called storage.After that i want to check with strstr if the "protypo" is appearing in storage and if it is print the line its appearing in.I dont understand what i am doing wrong and i would like a hand if possible. Thank you.

    int main()
    {
    int i,j,z;
    char x;
    char *pointstr;
    char protypo[101]={0};
    char input[101]={0};
    char storage[20][101]={{0}};       // An array of strings.


    printf("Give Protypo: \n");
    fgets(protypo,101,stdin);
    for (i=0;i<101;i++)
    {
            if (protypo[i]=='\n')
                    protypo[i]='\0';
            break;
    }
    printf("Give input: \n");

    for (i=0;i<5;i++)
    {
            fgets(input,101,stdin);
            strcpy(storage[i],input);       //Ta  string mou mesa se ena pinaka.

    }
    for (i=0;i<5;i++)
    {
            pointstr=strstr(storage[i],protypo);
            if (pointstr!=NULL)
            printf("Line protypo is appearing:\n %s",storage[i]);
    }
    }
Was it helpful?

Solution

for (i=0;i<101;i++) {
    if (protypo[i]=='\n')
        protypo[i]='\0';
    break;
}

doesn't look quite right. It checks that protypo[0] isn't a newline then exits the loop.

I guess you wanted to replace the first newline with a nul instead. You'd do this like

for (i=0;i<101;i++) {
    if (protypo[i]=='\n') {
        protypo[i]='\0';
        break;
    }
}

or, slightly more concisely,

char* c = strchr(protypo, '\n');
if (c != NULL) {
    *c = '\0';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top