-2

Here is the whole code, the problem is in the 25th line. If I give the value withe strcpy, the code works. If I try to read the value with fgets, the strstr in the 23th line doesn't work. Thanks for your help.

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

typedef struct tk {
    char name[60];
} tk;

int main() {
    tk* array;
    array = (tk*) calloc(1, sizeof(tk));
    int k;
    char c[60], h[60];
    strcpy(array[0].name, "A B");

    void find(char *c, tk *array) {
        for (k = 0; k < strlen(array[0].name); k++) {
            h[k] = tolower(array[0].name[k]);
        }
        printf("%s %s", array[0].name,c);
        if (strstr(h, c) != NULL) printf("1");
    }
    fgets(c, 60, stdin);
    k = 0;
    for (k = 0; (k < strlen(c)); k++) {
        c[k] = tolower(c[k]);
    }
    find(c, array);
    free(array);
    return (0);
}
mch
  • 9,424
  • 2
  • 28
  • 42
Noktua
  • 31
  • 1
  • 4
  • [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Dec 07 '16 at 09:11
  • `for (k=0;` --> `for (int k=0;`, at least. – Sourav Ghosh Dec 07 '16 at 09:12
  • 2
    You do realize that line numbers are not shown, right? A good idea is to mark with a code comment the place you're talking about, to make it easier to help you. – unwind Dec 07 '16 at 09:12
  • 2
    *"doesn't work"* is not suitable problem description. Please read about [mcve], [edit] your question and provide input you gave, output you got, and output you expected. – user694733 Dec 07 '16 at 09:12
  • 1
    are you actually using nested functions? that's non-standard. – Sourav Ghosh Dec 07 '16 at 09:13
  • 2
    `c` which was obtained from `fgets` contains a newline, but `"A B"` does not - so `strstr` will not find the substring. – Weather Vane Dec 07 '16 at 09:18
  • Thanks everybody. The problem was the the new line. Now can you help me how to delete it from c? As you can see I'm not a coding genius – Noktua Dec 07 '16 at 09:25

2 Answers2

1

The fgets man page says

fgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first.

That is why you get a match when you set up c with strcpy but not with fgets.

You can remove the newline like this

c [ strcspn(c, "\r\n") ] = 0;

and if there is no newline present, this is harmless.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
0

Add this line after the fgets. You need to remove the \n after reading it from stdin

fgets(c, 60, stdin);
strtok(c, "\n"); // add this statement

Tokenize the c array after reading it from stdin. Should work fine after this. Cheers!

sameera sy
  • 1,708
  • 13
  • 19