I need to count the characters in the comments from a C program, that is supplied as a standard input. This is my function, but for some reason it’s not counting right. Can you help me please?
int characters(FILE *file)
{
int i=0;
char ch[500], *p;
while (fgets(ch, sizeof(ch),file)!=NULL)
{
p=ch;
while (*p)
{
if (*p=='/')
{
p++;
if (*p=='*')
{
p++;
while (*p!='*' && *(p++)!='/')
{
i++;
p++;
}
}
}
else
p++;
}
return i;
}
I think the problem is in the innermost loop:
should be
But this will break if it sees something like this:
because the first part of the condition
*p!='*'will be false at the first asterisk, so you could do something like this instead:Note: if the line is broken you will get a segmentation fault:
you still have to deal with that but you should add
*pto the inner loop: