Vlad
Vlad

Reputation: 27

Counting specific chars in C?

while ((temp = fgetc(fp)) != EOF)
  {

  if(temp == '\n')
  {
      chars++;
      lines++;
      if((temp = fgetc(fp)) != EOF && (temp == '(' || temp == ')' || temp == '{' || temp == '}'))
          {
              chars++;
              brackets++;
          }
      }
  }

Basically I want to count every (),{} and lines in a random c file. This loop counts the lines just fine but fails to count all the specified symbols. Any idea why this is?

Upvotes: 0

Views: 76

Answers (3)

Nikola Smiljanić
Nikola Smiljanić

Reputation: 26863

while ((temp = fgetc(fp)) != EOF)
{
    if(temp == '\n')
        lines++;
    else if (temp == '(' || temp == ')') // include other brackets
        brakets++;

    chars++; // it appears that you want to count them all?
}

Upvotes: 1

Kaz
Kaz

Reputation: 58647

Consider a simple state machine structure like:

int ch;

while ((ch = getc(fp)) != EOF) {
  switch (ch) {
  case '\n':
     chars++;
     lines++;
     break;
  case '(': case ')': /* ... */
     chars++;
     brackets++;
     break;
  }
}

Upvotes: 3

while ((temp = getc(fp)) != EOF)
{
   chars++;
   if(temp == '\n')
   {
      lines++;
      continue;
   }
   if(temp == '(' || temp == ')' || temp == '{' || temp    == '}')
   {
          brackets++;
   }
 }

Upvotes: 1

Related Questions