i'm noob in C programming and I'm sorry for this question which could be very easy, but i cannot solve this problem after searching all the afternoon. I'm trying to write a program that generates a random number, checking that this is not already present in a list contained in the file number.txt. At the end the program has to ask if you want to extract another number and, if Yes, re-run it. I tried various for and while loops but none of these worked: numbers in the list are often extracted, What's wrong?
Moreover, sometimes, after various iterations, the program stops with the error "double free or corruption (! prev)", what causes it?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define rangeMAX 27 //Upper limit of range.
#define rangeMIN 1 //Lower limit of range.
int main()
{
int get, i, n;
int num[5];
char r;
FILE *filer;
filer = fopen("numbers.txt", "r");
printf("When you are ready press any key to continue\n");
getchar();
if (filer == NULL)
{
printf("ERROR Creating File!");
exit(1);
}
do {
num[5] = 0;
n = 0;
i = 0;
free(filer);
get = 0;
r = 0;
srand(time(0)); // this will ensure that every time, program will generate different set of numbers. If you remove this, same set of numbers will generated every time you run the program.
get = ((rand() % (rangeMAX-rangeMIN+1)) + rangeMIN); // generate random number.
for (n = 0; n < 5; n++){
fscanf(filer, "%d\n", &num[n]);
}
for (n = 0; n < 5; n++){
if (get == num[n]){
printf("false\n");
printf("%d\n", n);
break;
}
}
i=get;
printf("%d\n",i);
printf ("Do you want another number? Y/N ");
scanf (" %c", &r);
} while (r == 'y' || r == 'Y');
return(0);
}
Aucun commentaire:
Enregistrer un commentaire