Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi, I need help in a program that has to count the number of commented character

ID: 3882702 • Letter: H

Question

Hi, I need help in a program that has to count the number of commented characters and words in a C file input. the code below already counts the characters, how do I count the words by adding a case if *p == 'space'

/* 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

#include <stdio.h>
#include <string.h>
int main()
{
int i=0;
int count_word = 0;
char ch[500], *p;
FILE *file;
printf ("Enter the name of the file: ");
scanf ("%s", ch);
file = fopen(ch, "r");
FILE *file;
printf ("Enter the name of the file: ");
while (fgets(ch, sizeof(ch),file)!=NULL)
{
p=ch;
while (*p)
{
// Every time there is a space in the file , it implies that some particular word as ended.
// So when ever you see a space in the code add one to the counter that counts words.
// But what if there is only one word and in similar spirit , it doesn't include last word.
// So we will add a one to it at the end of the loop.

if (*p == ' ' || *p == ' ')
{
count_word ++;
}
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++;
}
}
}
count_word ++;
printf ("%d %d ", i,count_word); // prints the number of commented characters
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote