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;


      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);

      for (j = 0; j < 150; j++)

         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");


      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);

   return 0;

Edited by veselin.lalov.3

2 Years
Discussion Span
Last Post by Labdabeta

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.