-1
while((x= fgetc(p)) != EOF)
 {
  if (x== '/')
  {
      while((x = fgetc(p)) != EOF && x != '\n' && x != '/')
      {
          comments++;
      }
  }
}

Basically all I need is a way to count all the commented symbols in a file. This is the way i tried but it didn't work. Help is much appreciated :).

  • comments in c start with `/*` so you should be looking for this not just the single `/` – smac89 Jan 23 '14 at 01:40
  • And end with `*/`. If you don't check for both characters, you're going to flip state every time you hit division, or the use of `/` inside a string or a comment. And, as Smac89 says, end of line has nothing to do with ending a C comment. – keshlam Jan 23 '14 at 01:45
  • 2
    Adding to my previous comment, You have not given much information apart from `it does not work`. Can't do nothing 'bout that – smac89 Jan 23 '14 at 01:48
  • do you have to use plain C? I would rather learn Perl that try to reliably perform good pattern matching in plain C. especially if you plan on matching single line comments also... which are now part of the C std – Grady Player Jan 23 '14 at 01:48
  • Fair enough can you show me a way to properly count all the commented symbols? – user3225919 Jan 23 '14 at 01:48
  • @GradyPlayer Yes i do have to use plain C it's for a coursework im doing :/ – user3225919 Jan 23 '14 at 01:49
  • I really don't need something that will work flawlessly. I just need something that will work... somewhat ok-ish – user3225919 Jan 23 '14 at 01:59
  • You can search on SO with '`[c] strip comments`' as a search term. You will find a number of discussions. Stripping is similar to counting — you have to identify comments accurately. – Jonathan Leffler Jan 23 '14 at 02:18

1 Answers1

0

here is an example in ruby

cProg = %{#include <stdio.h>
#include <stdarg.h>
int main (int argc, char const *argv[])
\{
    printf("Hello World!");//hello world
    /* Some Multi

     Line Comment */

    return 0;

\}
}

matches = cProg.match(/\/\/.*$/)
cStyle = cProg.match(/\/\*[\s\S]*?\*\//)

print matches[0].length
print "\n"
print cStyle[0].length

edit

just saw that it has to be in C.. you will want to use strnstr and get the offset from successive "/*" and "*/" tokens as well as "//" to the next "\n" and subtract the pointers to get the lengths.

Grady Player
  • 14,399
  • 2
  • 48
  • 76