Hi, I need help in a program that has to count the number of commented character
ID: 3883157 • Letter: H
Question
Hi, I need help in a program that has to count the number of commented characters and commented words in a C file input. the code below already counts the commented characters, how do I count the commented words by adding a case if *p == 'space'. Also does this code works if both "//" and "/****/" apear in the input C file? Because I notice it uses (else if) for the second case.
/* program to print the number of commented characters */
#include <stdio.h>
#include <string.h>
int main()
{
int i=0;
char ch[500], *p;
FILE *file;
printf ("Enter the name of the file: ");
scanf ("%s", ch);
file = fopen(ch, "r");
while (fgets(ch, sizeof(ch),file)!=NULL)
{
p=ch;
while (*p)
{
if ((*p == '/')&& (*(p+1) == '/'))
{
p+=2;
while (*p && *p!= ' ')
{
i++;
p++;
}
}
else if (*p=='/')
{
p++;
if (*p=='*')
{
p++;
while (*p && !(*p=='*' && *(p+1)=='/'))
{
i++;
p++;
}
}
}
else
{
p++;
}
}
}
printf ("%d ", i); // prints the number of commented characters
}
Explanation / Answer
Yes it will work for both // and /*. Modified the code for words.
#include <stdio.h>
#include <string.h>
int main()
{
int i=0;
int count = 0;
char ch[500], *p;
FILE *file;
char a;
printf ("Enter the name of the file: ");
scanf ("%s", ch);
file = fopen(ch, "r");
while (fgets(ch, sizeof(ch),file)!=NULL)
{
p=ch;
while (*p)
{
if ((*p == '/')&& (*(p+1) == '/'))
{
p+=2;
while (*p && *p!= ' ')
{
i++;
if (*p == ' ')
count++;
p++;
}
if (*p == ' ' && *(p-1) != ' ')
count++;
}
else if (*p=='/')
{
p++;
if (*p=='*')
{
p++;
while (*p && !(*p=='*' && *(p+1)=='/'))
{
i++;
if (*p == ' ' || (*p == ' ' && *(p-1) != ' '))
count++;
p++;
}
}
}
else
{
p++;
}
}
}
printf ("%d ", i); // prints the number of commented characters
printf ("%d ", count); // prints the number of commented words
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.