[英]Counting characters in comments in c program
嗨,我想弄清楚如何计算c程序中注释中的字符。 到目前为止,我已经编写了一个无效的函数,但是看起来很合逻辑。 您能帮我完成任务吗,我的任务是用注释中的所有字符填充缓冲区,然后对它们进行计数。
void FileProcess3(char* FilePath)
{
char myString [1000];
char buffer[1000];
FILE* pFile;
int i = 0;
pFile = fopen (FilePath, "r");
while(fgets( myString, 1000, pFile) != NULL)
{
int jj = -1;
while(++jj < strlen(myString))
{
if ( myString[jj] == '/' && myString[jj+1] == '*')
{
check = 1;
jj++;
jj++;
}
if( check == 1 )
{
if ( myString[jj] == '*' && myString[jj+1] == '/')
{
check = 0;
break;
}
strcat( buffer, myString[jj] );
}
}
}
printf(" %s ", buffer );
fclose(pFile);
}
strcat()
连接(以NUL终止) 字符串 ,因此,这肯定是错误的(并且由于第二个参数的类型错误,应发出编译器警告):
strcat( buffer, myString[jj]);
你可以做类似的事情
buffer[length] = myString[jj];
buffer[length+1] = 0;
length++;
其中length
是一个初始化为零的整数,用于跟踪当前长度。 当然,您应该根据缓冲区的可用大小检查长度,以避免buffer(!)溢出。
如果您只想计算字符数,则根本不必将它们复制到单独的缓冲区中。 只需增加一个计数器。
您还应该注意, fgets()
不会从输入中删除换行符。 因此,如果您不想在计数中包括换行符,则必须进行检查。
例如修复
int i = 0, check = 0;
...
if( check == 1 )
{
if ( myString[jj] == '*' && myString[jj+1] == '/')
{
check = 0;
break;
}
buffer[i++] = myString[jj];
}
}
}
buffer[i]='\0';/* add */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.