您的位置:首页 > 其它

编译器练习:找出C程序中除注释外的数字并将其值翻倍

2009-03-22 13:56 309 查看
/*
programed by:alex shoal
edit date:2009-3-22, Sunday
revision:1
****************
*Program Objective:找出C程序中除注释外的数字并将其值翻倍
****************
*int,long,float,double,bool,char,
if,while,switch,case,continue,break,else,
void,unsigned,extern,global,default,
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char token[32];
int i;
int j;
int sz=0;
int temp=0;
int state=0;
char ch; // place to store each character as read
FILE *fp; // "file pointer"
if (argc != 2){
printf("Usage: %s filename/n", argv[0]);
exit(1);
}
if ((fp = fopen(argv[1], "r")) == NULL){
printf("Can't open %s/n", argv[1]);
exit(1);
}

while (((ch = getc(fp)) != EOF)){
i=0;
j=0;
sz=0;
switch(state){
case 0:{ if(ch=='/') state=1; break; }
case 1:{ switch(ch){
case '*': state=2;break;
case '/': state=4;break;
default : state=0;break;
}
break;
}
case 2:{ if(ch=='*') state=3;break; }
case 3:{ if(ch=='/') state=0;else state=2;}
case 4:{ if(ch==10 ) state=0;} //if ch == '/n', exit

}
if((!isdigit(ch))||state==2||state==4) putc(ch,stdout); //extern int isdigit(int c); 当c为数字0-9时,返回非零值,否则返回零
else{
for(i=0;i<32;i++) token[i]='/0';
i=0;
do{
token[i++]=ch;
ch=getc(fp);} while(isdigit(ch)&&ch!=EOF);

temp=atoi(token);
temp=temp*2;
sprintf(token,"%d",temp);
sz=strlen(token);
for(j=0;j<sz;j++){
putc(token[j],stdout);
}
putc(ch,stdout);
}
}

fclose(fp);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐