去掉C语言中的注释(《C程序设计语言》习题1-23)
来源:互联网 发布:温哥华华人 知乎 编辑:程序博客网 时间:2024/04/30 10:37
最近在看K&R的《C程序设计语言》(第2版)和川合秀实的《30天自制操作系统》,虽然有往Github上提代码,但没有写博客了。也不知道有什么可写的。
今天在《C程序设计语言》的习题答案中看到了1-23的一个测试用例,试了下发现我的答案有一个Bug,所以把Bug改掉了。
觉得值得小小的纪念一下,就把代码传到博客上来吧。
Exercise 1-23. Write a program to remove all comments from a C program. Don’tforget to handle quoted strings and character constants properly. C comments don’tnest. (Page 42)
#include <stdio.h>#define MAXLINE 1000char line[MAXLINE];int getline(void) { int c, i; extern char line[]; for ( i=0; i<MAXLINE-1 && ( c=getchar()) != EOF && c != '\n'; ++i) line[i] = c; if(c == '\n') { line[i] = c; ++i; } line[i] = '\0'; return i;}int main() { int comment = 0; // 注释 int doubleslash = 0; // 双斜线,注释 int quote2 = 0; // 双引号,字符串 int quote1 = 0; // 单引号,字符 int len; while((len = getline()) > 0) { for(int i=0; i<len-1; i++) { if(comment) { if(doubleslash == 0 && line[i] == '*' && line[i+1] == '/') { comment = 0; i++; } } else { if(line[i] == '\\') { putchar(line[i]); putchar(line[++i]); } else if(line[i] == '"') { if(quote1 == 0) quote2 = 1 - quote2; putchar(line[i]); } else if(line[i] == '\'') { if(quote2 == 0) quote1 = 1 - quote1; putchar(line[i]); } else { if(!quote2 && line[i] == '/' && line[i+1] == '*') { comment = 1; i++; } else if(!quote2 && line[i] == '/' && line[i+1] == '/') { comment = 1; doubleslash = 1; i++; } else { putchar(line[i]); } } } } if(!comment) putchar(line[len-1]); if(doubleslash) { doubleslash = 0; comment = 0; putchar(line[len-1]); } }}
0 0
- 去掉C语言中的注释(《C程序设计语言》习题1-23)
- C程序设计语言习题—1
- C程序设计语言习题1-12
- c程序设计语言习题1-9
- C程序设计语言1-9习题
- c程序设计语言习题1-9
- c程序设计语言习题1-10
- c程序设计语言 习题1-9
- c程序设计语言 习题1-12
- 【K&R 习题 1-23】删除C/C++语言中的程序中的所有注释语句
- C程序设计语言练习1-23 编写一个删除C语言程序中所有的注释语句
- c程序设计语言 课后习题
- 【C语言学习趣事】_29_《C程序设计语言》_Secnod_Edition_习题
- C程序设计语言(第二版)习题:第一章
- c语言中的注释
- C 语言状态机编程-去掉代码注释
- 习题课第一次作业:1、去除C程序中的注释
- 去掉c代码中的注释[转]
- POJ_1511_Invitation Cards【双向最短路】
- join,wait线程理解
- 在CentOS7下安装APACHE2.4.6
- EffectiveJava 概述
- 最长子序列
- 去掉C语言中的注释(《C程序设计语言》习题1-23)
- Problem 136. Single Number
- Zip命令
- “MvvmLightLibs”已拥有为“CommonServiceLocator”定义的依赖项。
- jquery选择器实现传入变量
- form表单的序列化及serialize()函数的使用
- Android常见异常处理整理
- WFU A
- java synchronized详解