1

This is my coplete project for anyone interested in more context: https://www.codepile.net/pile/LEYKzR0N

However I dont believe you need the whole code to answer this.

My function listGamesForPlayer reads a file that's format looks like this the file screenshot

The function scans for a name and returns only the line or lines that the name has been wrote in.

The function works perfectly fine but one problem is this. Lets say that in one line we have the name sara and in the other we have sarah. The function will display both the two names I don't want that.

So basically how can I make this code :

//this function lists all games for a player
int listGamesForPlayer()
{
    FILE *fp;
    char filename[]="results.txt",line[200],search_string[name];
    printf("\nEnter name to search for games: ");
    scanf("%s", search_string);
    printf("\nID |  X player  |  O player  |  Left Pieces\n\n");
    fp=fopen(filename,"r");

    while(fgets(line, 200, fp) != NULL){
        if(strstr(line,search_string))
        fputs(line, stdout);
    }
    fclose(fp);
    return 0;
}

Only take john and not johncena. So basically to cut somehow after the last letter.

Thank you in advance.

  • 2
    Append `,` to your search string. This conforms your file format. But your overall method is not well designed. I would suggest to first read and parse the whole file into a data structure, then work with this structure (assuming the file is not very big) – Eugene Sh. Jan 11 '21 at 18:44
  • 1
    Besides doing as suggested by @EugeneSh. you also need to add a space character before your search string. Something like `sprintf(new_search_string, " %s,", search_string);` – Support Ukraine Jan 11 '21 at 18:48
  • 1
    If I could upvote I would but I'm still new here. I don't know how I didn't think of that. Thank you so much! – Jovi Miljko Jan 11 '21 at 18:49
  • 1
    @4386427 Okay but why? – Jovi Miljko Jan 11 '21 at 18:51
  • 1
    If we say you look for something like "ben," it will also match "ruben," but if you look for " ben," it wont match " ruben," – Support Ukraine Jan 11 '21 at 18:53
  • @4386427 oh yeah that's great didn't think about that, Thank you! – Jovi Miljko Jan 11 '21 at 18:55
  • "works perfectly fine"....as long as all the input strings are short enough that you do not invoke undefined behavior, and if you assume valid permissions, etc. on the file. At the very least, you should put a maximum field width on the scanf conversion specifier so you don't overflow `search_string`. – William Pursell Jan 11 '21 at 19:01
  • @WilliamPursell i see your point thank you! – Jovi Miljko Jan 11 '21 at 19:51

0 Answers0