I want to get the occurence of the symbol ';' for each line of this C program. I type the name of the file Source.c and try to count the occuring symbol, but i am getting the value for ALL of the ';' for each line.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>/* For exit() function */

int main()

   char file_name[150];
   FILE *file2 = 0;

   gets(file_name);

   {
      int rows = 1;//broq na vsichki redove

      int dotcoma[150];
      int j;
      int c=0;

      file2 = fopen(file_name, "r");//otvarq faial za chetene
      if (file2 == NULL){
         printf("Cannot open %s\n", file_name);
         exit(2);
      }//if

      for (j = 0; j < 150; j++)
         dotcoma[j]=0;

      do{
         c = fgetc(file2);
         if (c == '\n') rows++;

         if (';' == c)

            dotcoma[rows-1] ++;



      } while (c != EOF);//chete do kraq na faila

      if (ferror(file2)){
         printf("Error reading file.\n");

      }//if

      printf("The number of the symbols on a row ");
      printf("Row %d: %f\n", j + 1, (float)dotcoma[j]);

   }

   if (fclose(file2) == EOF){
      printf("Cannot close %s\n", file_name);

   }
   _getche();
   return 0;
}

Edited 1 Year Ago by veselin.lalov.3

If you want to count the total numbers of ; in your file, don't use an array int dotcoma[150], just use a simple variable int dotcoma and increment it when you find a ;.
On the contrary, if you want to count the number of ; on each line, do what you are doing but, at the end, print all the array.

Your problem is that you are printing the number of semicolons (which is the correct name for 'dotcoma', its like a colon (':') but only half ';')

The line in question is

printf("Row %d: %f\n", j+1, (float)dotcoma[j]);

The issue here is three-fold.
1: j is uninitialized, some compilers will set j as 0, others as garbage, either way, its not what you want.
2: you cast dotcoma[j] to a float, this works but is terribly silly.
3: this line is not in a loop.

The solution will have to look something like this:

for (j= (|Insert start value here!|); j< (|Insert end value here!|); ++j)
    printf("Row %d: %d\n", j+1, dotcoma[j]);

Other than that, I would recommend consistent comparisons, either use c=='x' or 'x'==c but please don't switch between the two.

This article has been dead for over six months. Start a new discussion instead.