comparing the return value of fgetc() to a random digit

comparing the return value of fgetc() to a random digit



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



Just add '0' character to your digit:



Change


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



to


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






Thank you, i feel stupid for not having tought of that haha.

– Francis Poirier
Sep 16 '18 at 1:19






You can just add '0' to be more explicit, instead of having a seemingly random 48 in your code

– Nic
Sep 16 '18 at 1:20


'0'






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.

– chux
Sep 16 '18 at 1:36



rand()%((6-1)+1)


'0'






There is no guarantee ASCII is used for the character set. And don't use magic numbers in code!

– too honest for this site
Sep 16 '18 at 11:18



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)