/*
去除C程序中的注释
查看 提交 统计 提问
总时间限制: 1000ms 内存限制: 65536kB
描述
C程序的注释用/*...*/来表示。请写一个程序,将输入的C程序源代码中的注释去掉,输出去掉注释之后的源代码。
用于测试的C代码保证符合语法,不使用C++的//注释语法。
注意,C语言不允许出现嵌套注释。具体来说,对于/*/**/"*/",如果不允许嵌套注释,那么它表示字符串"*/";如果允许嵌套注释,它表示一个引号"。
还请注意,字符串中出现的注释符/*属于字符串的一部分,注释中出现的双引号"属于注释的一部分。
输入
符合语法的C代码文本文件。代码每行不超过200个字符。
输出
去掉注释后的C代码。要求只能去掉注释,不可以做其他的修改,比如调整缩进,去除注释之外的换行符等。
提示
注意字符串,字符,转义字符的情况。
看看自己有没有考虑
"a\"/*ccc*/"
这种情况。
*/
#include
#include
int main()
{
char temp_ch;
bool in_annotation = 0;//是否在注释中
bool in_string = 0;//是否在字符串中
while (scanf("%c", &temp_ch) != EOF)
{
if(!in_annotation)
{
if (!in_string)
{
while (temp_ch == '/')//特别注意///*的情况
{
scanf("%c", &temp_ch);
if (temp_ch == '/') printf("/");
else if (temp_ch != '*' && temp_ch != '"') printf("/");
else if (temp_ch == '*') in_annotation = 1;
}
if (!in_annotation)
{
if (temp_ch == '"')
{
in_string = 1;
}
printf("%c", temp_ch);
}
}
else //在字符串中 需考虑转义 以及字符串的终点
{
if (temp_ch == '\\')//转义的情况 可以直接忽略\后面的字符,不处理直接输出
{
char temp_ch2;
scanf("%c", &temp_ch2);
printf("%c%c", temp_ch, temp_ch2);
}
else
{
if (temp_ch == '"')
{
in_string = 0;
}
printf("%c", temp_ch);
}
}
}
else//在注释中的情况 只要判断是否为注释结束的位置
{
while (temp_ch == '*')//特别注意***/的情况
{
scanf("%c", &temp_ch);
if (temp_ch == '/') in_annotation = 0;
}
}
}
return 0;
}