2

I've been set on a task to read the list of numbers from an external file and display statistics on it. My initial plan was to count how many times a specific value has appeared in the code but I encountered two problems: my output of the external file was different to the values on the file and I'm not able to count the individual numbers in this code using the for loop down below. Thanks in advance.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
  FILE *fpointer;
  fpointer = fopen("randice.txt","r");
  char filename[600];
  int v, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0;

  while (!feof(fpointer))
  {
    fgets(filename,600,fpointer);
    puts(filename);
  }

  for(v=0;v<600;v++)
   {
     if (filename[v] == 1)
     c1++;
     if (filename[v] == 2)
     c2++;
     if (filename[v] == 3)
     c3++;
     if (filename[v] == 4)
     c4++;
     if (filename[v] == 5)
     c5++;
     if (filename[v] == 6)
     c6++;
   }
  fclose(fpointer);
  
  return 0;
}
Tee
  • 25
  • 5
  • Please give the exact input, expected result and actual result. Also, what debugging have you done and what did you find? – kaylum Dec 14 '20 at 04:56
  • 1
    `if (filename[v] == 1)`. Note that `1` is an integer which is different to `'1'` which is an ascii character. If you are reading a text file it is the latter which is stored and not the former. – kaylum Dec 14 '20 at 04:59
  • 1
    First of all please read [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) Then take some time to think about the contents of `filename` *after* the reading loop (or just in general). Why makes you think that an ASCII (most likely) character would be equal to e.g. `1` instead of `'1'`? Lastly, please think about the variable *name* `filename`. Is that really a descriptive name of what you use the variable for? – Some programmer dude Dec 14 '20 at 04:59
  • @kaylum Im expected to get 96 for the number of times the number 1 has been counted but I've gotten 2 using this program etc. In total there are 600 values in each line from 1 - 600. Should i send a text file which shows all the random values? – Tee Dec 14 '20 at 05:02
  • You don't need to test with 600 numbers as the code is not correct even for a small set of inputs. So for posting here and, even more importantly, for your own debugging reduce the data input to the minimum needed. In fact, your code will fail even for a file containing a single number due to the ascii vs binary misunderstanding that has already been pointed out to you. – kaylum Dec 14 '20 at 05:07

1 Answers1

1

Word frequency statistics in C:

A more advanced example is in https://rosettacode.org/wiki/Word_frequency#C

ralf htp
  • 9,149
  • 4
  • 22
  • 34