-1

I am trying to read a file until i hit a random int between 1 and 5 and then read the word next to that int into an array. Before trying to compare a random int with the return value of fgetc(), the code was working well (It read chars into an array until an end of line). Now, when i am in the debugger, i see that the return value of fgetc() for the integers i am looking for is the ASCII decimal value, not the actual integer. So when i compare with the random int, it is never found. I don't understand how to get this right. Here is the code, sorry for the comments being in french, they are not relevant.

int lectureMot(FILE *listePtr, char motsecret[])
{
    int caracLu;
    int nbLettres = 0;
    int numRand;
    numRand = rand()%((6-1)+1);

    /*Ouverture du fichier texte de la liste*/
    listePtr = fopen("Liste.txt","r");

    /*Verification de l'ouverture du fichier*/
    if (listePtr == NULL)
    {
        printf("Erreur a l'ouverture de la liste");
        return(EXIT_FAILURE);
    }
    else
    {
        /*Lire jusqu'au nombre random*/
        while((caracLu = fgetc(listePtr)) != numRand);

        /*Lire le mot et le mettre dans le tableau*/
        while((caracLu = fgetc(listePtr)) != '\n')
        {
            motsecret[nbLettres] = (char)caracLu;
            nbLettres = ++nbLettres;
        }
    }
    /*Fermeture du fichier liste*/
    fclose(listePtr);
    return nbLettres;
}

1 Answer 1

0

Just add '0' character to your digit:

Change

numRand = rand()%((6-1)+1);

to

numRand = (rand()%((6-1)+1)) + '0';
4
  • Thank you, i feel stupid for not having tought of that haha. Sep 16, 2018 at 1:19
  • 5
    You can just add '0' to be more explicit, instead of having a seemingly random 48 in your code
    – Nic
    Sep 16, 2018 at 1:20
  • 1
    rand()%((6-1)+1) will not generate the random number 1-5, instead it makes 0 - 5. Adding 48 instead of '0' would not pass many a code-review. Sep 16, 2018 at 1:36
  • 1
    There is no guarantee ASCII is used for the character set. And don't use magic numbers in code! Sep 16, 2018 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.