-2

我需要从文件中获取问题,然后随机显示它们以输入答案。我所做的是生成一个随机数,然后文件逐行读取。当它遇到随机数时,它将显示相关行。现在一切正常,但我不想重复数字。我该如何解决这个问题。

这是我尝试过的

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

1 回答 1

1

未初始化的变量和未初始化的数组ar将导致未定义的行为。

该文件只需要打开一次。用于rewind回到起点。

如评论中所述,srand仅使用一次。并且您已将数组大小传递给函数,因为foo(int ar[])大小ar是指针大小,而不是分配大小。

只需检查随机数是否已被使用。如果不使用,则将其存储在数组中。随机数的范围和数组大小应该完全匹配。不要添加+1

int main(void)
{
    srand((unsigned int)time(NULL));
    FILE *pToFile = fopen("data.txt", "r");
    char input[512];
    int line;
    int arr[5];
    int array_size = sizeof(arr) / sizeof(arr[0]);

    for (int count = 0; count < array_size; count++)
    {
        arr[count] = -1; // initialize to -1 to indicate it is not set
        while(arr[count] == -1)
        {
            arr[count] = rand() % array_size;
            for(int i = 0; i < count; i++)
                if(arr[i] == arr[count])
                    arr[count] = -1;
        }

        rewind(pToFile);
        line = 0;
        while(fgets(input, 512, pToFile))
        {
            if(line++ == arr[count])
            {
                printf("%s", input);
                break;
            }
        }
    }

    fclose(pToFile);
    return 0;
}
于 2017-11-17T05:38:10.580 回答