jeudi 16 novembre 2017

Get data from a file and randomly show lines without duplicating in C

I need to get Questions from a file and then randomly show them to enter answers. What I have done was I generate a random number and then file is reading line by line.When it meets the randomize number it will shows the relevant line. now all working but i don't want to duplicate numbers.How can I fix this.

Here what i tried

   int main()
{
    int numb;
    int answer;
    int ar[5];
    int count =0;

    numb = randomgen();
    ar[count]=numb;
    char input[512];

    printf("Line number to print :%d\n",numb);
    count++;
    while(count != 6)
    {
        FILE * pToFile= fopen("data.txt","r");
        int line =0;
        while(fgets(input,512,pToFile))
            {
                line++;
                if(line == numb)
                {
                    printf(" %s",input);
                }

            }

            printf("Enter the answer:");

            scanf("%d",&answer);
            printf("\n");
            answermethod(numb,answer); //to check the answers ;WORKING

            numb = randomgen2(ar);
            ar[count] = numb;
            count++;

            fclose(pToFile);
    }

    return 0;

}
    int randomgen()
    {
         int r;
    srand(time(NULL));
    r=rand()%(5)+1;
    return r;

    }


    int randomgen2(int ars[]) //generate random n and search it in the 
                            //array if it is not in array return the random 
                            //  value.But this is not working
    {
    int r;
    srand(time(NULL));
     r=rand()%(5)+1;
    int num,i,c=0;

    int n= sizeof(ars)/sizeof(ars[0]);
          for(i=0;i<n;i++)
          {
              if(ars[i]==r)
              {
                  //printf("%d",r);

                  randomgen2(ars);
                  c=1;
                  break;
              }

              else
              {
                   printf("not found%d",r);
                  c=0;
              }
          }

            if(c==0)
            {
                printf("nooo");
                return r;
            }
    }




Aucun commentaire:

Enregistrer un commentaire