题目:
编写一个删除c语言程序中所有的注释语句。要正确的处理带引号的字符串与字符常量。在c语言中注释不允许嵌套
首先需要理解什么是注释嵌套,c语言中有两种注释符,一种是行注释符//,一种是块注释符/**/
其中行注释符,一次只能注释一行,//之后的全部为注释
块注释符要成对出现,注释从/*开始到*/结束。
注释嵌套是指对块注释符所说,例如下面为注释嵌套的例子:
/* /* this is the comments */ */
注释从第一个/*开始,到第一个*/结束。所以最后一个*/不在注释范围内,这种注释是不被允许的,否则会导致编译错误
自我解答:
#include <stdio.h>
#define IN 1
#define OUT 0
int main()
{
int c;
bool comInStr = OUT; //the comment symbol // or /* in the string
bool blockCom = OUT; // the character is in comment block "/**/"
bool lineCom = OUT; // the character is in a comment line "//"
bool isComSymbol = false; // if it is comment symbol "//" or "/*"
bool outComBlock = false; //the flag for out of comment block
while((c = getchar()) != EOF)
{
if(comInStr)
{
putchar(c); //output the content in " "
if(c == '"')
comInStr = OUT; //end of the content in " "
}
else
{
if(lineCom == IN)
{
if(c == '\n') // will not output until to the end of the line
{
putchar(c);
lineCom = OUT;
isComSymbol = false;
}
}
else if(blockCom =