[英]C program that counts the number of characters in the comments
您好,我正在制作一个C程序,用于对源文件注释中的字符数进行计数,而在计数中添加'/ ',' /'字符。 我的代码似乎只计算int main()函数之前的注释。 有人可以给我一些如何解决此问题的指导吗?
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <string.h>
#include <conio.h>
//hi/
int main()
{
//hi/
char filename[199];
char c[1000];//hi/
FILE *filep;
int comments = 0;
gets(filename);
if (!(filep = fopen(filename, "r")))
{
fprintf(stderr, "Error! File %s not found\n", filename);
return;
}
while (fgets(c, sizeof(c), filep) != 0)
{
int len = strlen(c);
for (int i = 0; i <= len; i++)
{
if (c[i] == '/' && c[i] == '/')
{
comments += (strlen(c) - 2);
break;
}
if (c[i] == '/' && c[i] == '*')
comments += (strlen(c) - 2);
break;
}
}
fclose(filep);
printf("%s: Number of characters in comments: %d\n", filename,comments);
_getche();
return 0;
}
您必须比较两个字符。 使条件如下。
if (c[i] == '/' && c[i+1] == '/')
if (c[i] == '/' && c[i+1] == '*')
由此您可以检查当前字符和下一个字符。
然后在for循环中使用break语句。 您是否期望套票必须运行一次。 删除break;
因为注释位于行中的任何位置。 如果您只想检查一次,请不要删除break;
,然后使for循环为
for (int i = 0; i < len-1 ; i++)
这要感谢@ Karthikeyan.RS代码正在运行。 添加了一些随机注释以对其进行测试。
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <string.h>
#include <conio.h>
/*hi*/
int main()
{
char filename[199];
char c[1000];
FILE *filep;
int comments = 0;
gets(filename);
/*hi*/
/*hi*/
/*hi*/
if (!(filep = fopen(filename, "r")))
{
fprintf(stderr, "Error! File %s not found\n", filename);
return;
}
//hi/
while (fgets(c, sizeof(c), filep) != 0)
{
int len = strlen(c);
for (int i = 0; i < len - 1; i++)
{
if (c[i] == '/' && c[i+1] == '/')
{
comments += (strlen(c)-3-i );
}
if (c[i] == '/' && c[i + 1] == '*')
comments += (strlen(c) - 5 - i);
}
}
fclose(filep);
/*hi*/
printf("%s: Number of characters in comments: %d\n", filename,comments);
_getche();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.