Reading values from file stream to an array (C) -
i have been thinking on while. given assignment says following:
there text file containing numbers. (min, max, number) have read contents of file, generate random number between min , max. if generated number matches number, print "match."
min: 7 max: 17 number: 15 ...
i able read every number array, code:
int main(void) { srand(time(null)); int nums[50] = {0}; int = 0; file * fp; /*if(fp == null) return 1;*/ if (fp = fopen("numbers.txt", "r")) { while (fscanf(fp, "%d", &nums[i]) != eof) { ++i; } fclose(fp); } (--i; >= 0; --i) printf("num[%d] = %d\n", i, nums[i]); return 0; }
however, have no idea how continue. how can assign specific values random number generator function?
int random(int min, int max) { return rand()%(max-min+1)+min; }
solution -
you shouldn't use array since don't need store numbers, need see them once accomplish task. can calculate random number within our constraints read in numbers. let's this:
int main(void) { srand(time(null)); int nums[50] = {0}; int min = 0, max = 0, match= 0; file * fp; fp = fopen("numbers.txt", "r") if(fp == null) { return 1; } // compare return value of fscanf 3 make sure // 3 values read in file during each // iteration. while (fscanf(fp, "%d %d %d", &min, &max, &match) == 3) { if(random(min, max) == match) { printf("match.\n"); } else { //no match! } } fclose(fp); return 0; } int random(int min, int max) { return rand() % (max - min + 1) + min; }
a few other issues code improved:
what using
srand
for? don't see used, i'll take out bit of code. no need distractions.srand(time(null)); // removing line.
why have initialized
nums
{0}
? makes purpose unclear, , should leave uninitialized.int nums[50] = {0};
could be:
int nums[50];
we can clean initial part of file opening, from:
/*if(fp == null) return 1;*/ if (fp = fopen("numbers.txt", "r")) { ... }
to this:
fp = fopen("somenumbers.txt", "r"); if(fp == null) { //tell user error occured. return 1; }
Comments
Post a Comment