题目描述
C语言的注释分为两种,第一种:在一行源代码中“//”后的内容为注释内容。第二种:“/”与“/”之间的内容为注释内容。第三种:程序中只出现了“/”,没有“/”与之对应,那么将“/”后的全部内容都要过滤掉。注意,只要是注释内容,那么注释内容中的字符应该全部忽略,即不起任何的作用。例如“/”与“/”之间如果再有“//”,那么“//”不应起作用;如果“//”再有“/”,那么“/”也不应起作用。
你的任务是先打开一个名字为dict.dic的文本文件,该文件中前5行每行为1个整数,从第6行开始为5段C语言的源代码。那5个数字代表这5段源代码结束的行数,比如如果第一行的整数为20,第二行的整数为60,则表示从第6行到第20为第一段代码,从第21行到第60为第二段代码。然后根据输入要求将源代码中所有注释过滤掉。
在本过滤注释系统中,你可以忽略源文件中双引号导致“//”、“/”、“/”失去作用的情况,即只要“//”、“/”、“/”不是注释内容,在任何情况下都起作用。
输入
只可能是1,2,3,4,5之一
输出
输入为1则输出第一段代码过滤后的结果,输入为2则输出第二段代码过滤后的结果,依此类推。
样例输入
1
样例输出
如果第一段代码是这样:
/*
@Author: BUPT
@Date: 2010 8 26
*/
#include<stdio.h>
int main()
{
int a = 10 , b = 2 , c ;
c = a / b ; //I just want to test ‘/’
printf(“I love programming C.\n”) ; //“printf” is a useful function /*
printf(“I hope you love it too!\n”) ;
/*
//C is not always hard , if you love it , it will not treat you rough.
*/
return 0 ;
}
则输出是这样:
#include<stdio.h>
int main()
{
int a = 10 , b = 2 , c ;
c = a / b ;
printf(“I love programming C.\n”) ;
printf(“I hope you love it too!\n”) ;
return 0 ;
}
源代码
#include <stdio.h>
#include <stdlib.h>
int findHead(FILE * ,int);
int findLast(FILE * ,int);
void deleteState(FILE **,int * ,int *);
void deleteLine(FILE **,int *,int *);
int main(){
FILE * fp = fopen("dict.dic","r");
int start,end;
if(fp != NULL){
int a,b,c,d,e;
fscanf(fp,"%d",&a);
fscanf(fp,"%d",&b);
fscanf(fp,"%d",&c);
fscanf(fp,"%d",&d);
fscanf(fp,"%d",&e);
int mode;
scanf("%d",&mode);
switch (mode)
{
case 1:
rewind(fp);
start = findHead(fp,5);
rewind(fp);
end = findLast(fp,a);
break;
case 2:
rewind(fp);
start = findHead(fp,a);
rewind(fp);
end = findLast(fp,b);
break;
case 3:
rewind(fp);
start = findHead(fp,b);
rewind(fp);
end = findLast(fp,c);
break;
case 4:
rewind(fp);
start = findHead(fp,c);
rewind(fp);
end = findLast(fp,d);
break;
case 5:
rewind(fp);
start = findHead(fp,d);
rewind(fp);
end = findLast(fp,e);
break;
default:
printf("??");
break;
}
rewind(fp);
while(ftell(fp)<start) fgetc(fp);
while(ftell(fp) != end){
int currentch = fgetc(fp);
int flag = 1;
if(currentch == '/' ){
int nextch = fgetc(fp);
if(nextch == '*'){
while(flag && ftell(fp) != end){
currentch = fgetc(fp);
while(currentch == '*' && ftell(fp) != end){
currentch = fgetc(fp);
if(currentch == '/' && ftell(fp) != end) flag = 0;
}
}
}
else if(nextch == '/'){
while(currentch != '\n'){
currentch = fgetc(fp);
}
}
else {
printf("%c",currentch);
currentch = nextch;
}
}
if(ftell(fp) != end && flag) printf("%c",currentch);
}
}
fclose(fp);
return 0;
}
int findHead(FILE * fp,int line){
int ch = 0;
while(line-- && ch != EOF){
ch = fgetc(fp);
while(ch != '\n' && ch != EOF){
ch = fgetc(fp);
}
}
return ftell(fp);
}
int findLast(FILE * fp,int line){
int ch = 0;
while(line-- && ch != EOF){
ch = fgetc(fp);
while(ch != '\n' && ch != EOF){
ch = fgetc(fp);
}
}
return ftell(fp);
}
教训
文件指针指向的好像并不是文件中的字符。。所以只能用ftell()函数来判断自己是否到了要判断的范围的开头与末尾