Hi. can someone help me with my homework. this is a C language in a UNIX homewor
ID: 3871626 • Letter: H
Question
Hi. can someone help me with my homework. this is a C language in a UNIX homework. we need a C program, to count the number of commented characters in an input C file.
Here is my unfinished work, I tried to read a helloworld file, but can't figure out how to count its commented characters, for cases: "//" and "/******/"
int main() {
FILE * fp;
fp = fopen("hello.c", "r");
int c = 0;
int nc = 0;
while ((c = fgetc(fp)) != EOF ) {
if (c == '/') {
nc++ } // Just checking if the reading works. So I count the number of '//'
putc(c, stdout); //Still checking, try to print out the whole input C file.
}
printf(" the number of comment slashes are: %d", nc); // this printed 6, because my hello.c has 6 '/' for comments.
fflush(stdout);
fclose(fp);
return 0;
}
In this draft I tried to explicitly input hello.c. But the program has to read any C file input in the same folder and read its comment characters. the number of commented characters should be printed.
Explanation / Answer
int main() {
int i = 0; // stores the number of commented characters
char ch[900], *p;
scanf("%s",&ch); // stores file name
fread(ch, sizeof(char), 900, file); //reads file and stores it in ch[]
p = ch; //store pointer for ch which traverses the entire file
while (*p)
{
if (*p=='/' && *(p+1) == '*')
{
while (*p && (*p != '*' && *(p+1) != '/'))
++p;
++i;
}
++p;
}
printf("%d",i); //prints the number of commented characters
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.