簡體   English   中英

將 fgetc() 的返回值與隨機數字進行比較

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

我正在嘗試讀取一個文件,直到我在 1 到 5 之間找到一個隨機 int,然后將該 int 旁邊的單詞讀入數組。 在嘗試將隨機 int 與 fgetc() 的返回值進行比較之前,代碼運行良好(它將字符讀入數組直到行尾)。 現在,當我在調試器中時,我看到我正在尋找的整數的 fgetc() 返回值是 ASCII 十進制值,而不是實際的整數。 所以當我與隨機整數進行比較時,它永遠不會被找到。 我不明白如何做到這一點。 這是代碼,很抱歉評論是法語,它們不相關。

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;
}

只需在您的數字中添加“0”字符:

改變

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM