第二次笔试遇到这个题了,没办法,虽然麻烦点,练习一下吧。可能还有没考虑全的情况。
要求:去除cpp源文件中的注释
输入:input.cpp
输出:output.cpp
// EX037.cpp : Defines the entry point for the console application.
//
/*
功能:去除注释
输入:input.cpp
输出:output.cpp
*/
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
FILE *fp1=fopen("input.cpp","r");
FILE *fp2=fopen("output.cpp","w");
char ch1='\0';
char ch2='\0';
while(EOF!=(ch2=fgetc(fp1))){
if(ch2=='/'){
if(ch1=='/'){
while(EOF!=(ch2=fgetc(fp1))){
if(ch2=='\n'){
ch1='\0';
ch2='\0';
break;
}
}
}else{
ch1=ch2;
}
}else if(ch2=='*'){
if(ch1=='/'){
ch1='\0';
while(EOF!=(ch2=fgetc(fp1))){
if(ch2=='/'){
if(ch1=='*'){
ch1='\0';
ch2='\0';
break;
}
}else{
ch1=ch2;
}
}
}
}else if(ch2=='\"'){
fputc(ch2,fp2);
printf("%c",ch2);
while(EOF!=(ch2=fgetc(fp1))){
fputc(ch2,fp2);
printf("%c",ch2);
if(ch2=='\"'){
break;
}
}
}else{
if(ch1=='/'){
fputc(ch1,fp2);
printf("%c",ch1);
ch1='\0';
}
printf("%c",ch2);
fputc(ch2,fp2);
}
}
fclose(fp1);
fclose(fp2);
return 0;
}
测试文件如下:
input.cpp
// EX037.cpp : Defines the entry point for the console application.
//
/*
功能:去除注释
输入:input.cpp
输出:output.cpp
*/
#include "stdafx.h"
#include <stdio.h>
int main(int argc, char* argv[])
{
FILE *fp1=fopen("input.cpp","r");
FILE *fp1=fopen("output.cpp","w");
printf("/////");
return 0;
}
结果为:
output.cpp
#include "stdafx.h"
#include <stdio.h>
int main(int argc, char argv[])
{
FILE fp1=fopen("input.cpp","r");
FILE fp1=fopen("output.cpp","w");
printf("/////");
return 0;
}
2227

被折叠的 条评论
为什么被折叠?



