C Reading numbers from file and placing them in range bins and printing to file -


i'm having issue program.

what i'm trying read lines file input.txt, first line number of integers in file. input.txt formatted

5 //num of ints
2
40
49
90
70

then, want print file output.txt output.txt basically.

range 0-9 1
range 10-19 0
range 20-29 0
range 30-39 0
range 40-49 2
range 50-59 0
range 60-69 0
range 70-79 1
range 80-89 0
range 90-99 1

the ranges go 99. there 10 ranges. there never number on 99 after initial line in input.txt.

the issue i'm having program works fine long number of guesses 10. know has how set range numbers increase, since it's tied loop. i'm lost on how properly.

any advice? thanks, in advance!

what i've got far:

/*  print numbers in range file output.txt list of numbers in file input.txt  */  #include <stdio.h>  int main(void) {  file *input; file *output;  int num_guesses, nums, bin_count=0, guesses_in_bin; int i, j, k, firstline; int bin_start = 0; int bin[10];   input= fopen("input.txt", "r"); output= fopen("output.txt", "w");  fprintf(output, "values        amounts\n");  fscanf(input, "%d", &num_guesses); //scans first line of input.txt number of guesses  (j=0; j< (num_guesses); j++) //for number of guesses run inside loop  {      (i=0; i< (num_guesses); i++)     {         fscanf(input, "%d", &nums);         //printf("            %d\n", nums);         if (nums >= bin_start && nums <= bin_start+9) //checks if number belongs in bin.             bin_count = bin_count+1;           }     //rewind     rewind(input);     fscanf(input, "%d", &firstline); // used ignore first line of file       //reset bin count     numbers_in_bin = bin_count;     bin_count = 0;       fprintf(output, "%2d - %2d      %d", bin_start, bin_start+9, numbers_in_bin);      fprintf(output, "\n");      //update next bin      bin_start = bin_start+10;     }     fclose(input); fclose(output);    return 0; } 

without looking more-or-less subtle bugs, stop right here, solution wrong in concept. sane way solve create counters all ten possible bins in advance like:

int bin[10] = { 0 }; 

then scan file one time , simple as

bin[input/10]++; 

for output, loop on bins, eg:

for (int = 0; < 10; ++i) {     printf("%d-%d:\t%d\n", 10*i, 10*i+9, bin[i]); } 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -