Search code examples
cwhile-loopscanfstrcmp

strcmp and fscanf with a While Loop through a file


I'm having trouble with a specific line of code that is giving me the errors of

error: invalid conversion from ‘int’ to ‘const char*’

error: initializing argument 1 of ‘int strcmp(const char*, const char*)’

Does anyone happen to know why? This is the line of code in question.

while (strcmp(fscanf(fr, "%s", words), "DONE") != 0)

Essentially, my code scans through a file (performing certain operations) until it reaches the key word of "DONE" (without the quotes), at which it exits the file. I'm a beginner C programmer so forgive any inaccuracies/inefficiencies in code.

The full code is below.

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

FILE *fr;

struct player {
    char name[50];
    float DOC;

};

struct player players[50];

int main() {
    fr = fopen ("playerinfo.txt", "r");

    if (ftell(fr) == 0) {
        fclose(fr);
        printf("PLAYER FILE IS EMPTY");
        return 0;
    }

    char words[50];

    while (strcmp(fscanf(fr, "%s", words),"DONE") != 0) {
        float pts;
        fscanf(fr, "%f", pts);

        float asts;
        fscanf(fr, "%f", asts);

        float mins;
        fscanf(fr, "%f", mins);

        struct player *aPlayer;
        float theDOC = (pts + asts) / mins;
        strcpy(aPlayer->name, words);
        aPlayer->DOC = theDOC;
    }

    fclose(fr);

    return 0;
}

Solution

  • In your code,

      strcmp(fscanf(fr, "%s", words),"DONE")
    

    does not do what you think it does. fscanf() does not return a pointer to the scanned string, rather, it returns a count (int type). Your compiler warned you. Read the man page before you proceed.

    This improper usage causes the warning.

    That said, you must check for the success of scanf() family of functions, otherwise, you have a very high possibility of ending up with using indeterminate values (think of the content of words, if scanning fails).

    So, you break the operations into two parts.

    • use fgets() / fscanf() to intake the input (newline trimming, if needed). Check for success of the call.
    • compare the input buffer with the required string (strcmp()).

    That said, I really don't see much point of the whole loop, as you'll be creating a new local variable aPlayer every time you enter the loop. I hope you know what you're doing.

    Disregarding above case, a generic flow should look like

    input = "Not Done";
    while ('input' is not "Done")
         scan values;
         check for succss;
         store into variables;
         scan next 'input'