HE
发布时间: 2017年3月27日 18:28 最后更新: 2017年3月27日 18:30 时间限制: 1000ms 内存限制: 256M
"Hi there, my name is HE."
在某个秘密的计算机实验室中,超级人工智能计算机 HE 诞生了。
HE 可以在网络中搜索合适的程序代码进行自我升级。在某次升级的过程中,HE 得到了一堆软件代码,其中有很多注释和空行。注释是为了人类能够读懂代码而写的,而对于 HE 来说,它并不需要这些东西,因此它会首先删除掉代码中的所有注释以及空行。
这里定义了2种注释格式:
1.行注释“//”:符号“//”之后直至行尾的所有内容都被认为是注释部分;
2.段注释“/\* ... \*/”:“/\*”表示段注释开始,“\*/”表示段注释结束,其间的所有内容都被认为是注释部分。
科学家发现 HE 的编译器分析部分出现了一些小问题,现在他们希望你能够编写程序帮助 HE 完成这一步骤。
输入文件只有一个,其中有许多包含注释的语言代码,请读至文件末尾(EOF)。
输出删除掉注释之后的代码。
注:
1.若某一行删除完注释之后只剩下空格,则该行也将被视作一个空行,需要一起删除。
2.需要同时删除行末的空格。
#include<stdio.h> //test int main() {printf("Helloworld.");return 0; } #include<stdio.h> /* ---- ---- */int main() {// testprintf("Goodluck."); // testreturn 0; /* -- */ }
#include<stdio.h> int main() {printf("Helloworld.");return 0; } #include<stdio.h> int main() {printf("Goodluck.");return 0; }
step1()函数用于去除// 以及/**/这类的注释,把要删除的地方标记为1,输出的时候不输出就可以了
step2()函数用于去除多余的空格以及换行。
思路如下:
每次从一行的开头检测,直到检测到'\n'为止,用pre表示该行第一个空格的位置,如果这一行中有非空格字符,那么标志位f = 1
该行检测完成以后把beg 到 \n区间全部删除掉(置值为1),然后判断f是否为1,如果不为1,那么\n也要删除掉
#include <cstdio>
#include <iostream>
using namespace std;
char str[1000000];
int length;
void read()
{char c;while(~scanf("%c",&c))str[length++] = c;str[length++] = '\n';str[length] = 0;
}
void step1()
{char c = str[0];int pos = 0;while(c){if(c == '/'){if(str[pos + 1] == '/')while(str[pos] != '\n') str[pos++] = 1;else if(str[pos + 1] == '*'){while(str[pos + 2] != '*' || str[pos + 3] != '/') str[pos++] = 1; str[pos] = str[pos + 1] = str[pos + 2] = str[pos + 3] = 1;}}c = str[++pos];}
}
void step2()
{char c = str[0];int pos = 0;while(true){if(pos == length) break;int f = 0;int beg = pos;//本行第一个字符 for(;str[pos] != '\n';pos++){if(str[pos] == 1) continue;//已经被删除过的字符不必考虑在内 if(str[pos] != ' ') {beg = pos + 1;f = 1;}}//pos 指向/nfor(int i = beg;i < pos;i++) str[i] = 1; if(!f) str[pos] = 1;pos ++;}str[length-1] = 1;
}
void print()
{int pos = 0;while(str[pos]){if(str[pos] != 1) putchar(str[pos]);pos++;}
}
int main()
{freopen("test.txt","r",stdin);freopen("out.txt","w",stdout);read();step1();step2();print();
}