實(shí)現(xiàn)去除c語言注釋的小工具
去除C代碼中的注釋,
1. 單行注釋//;
2. 多行注釋/**/;
3. 單行注釋以“\”結(jié)尾則下一行也為注釋;
4. 字符串中的注釋不處理。
說是C語言,但其實(shí)所有C語系的都可以,比如Java。
小工具:去除C語言注釋
#include <stdio.h>
int main(int argc, char* argv[]) {
enum {
literal,
single,
multiple,
string
} mode = literal;
char last = 0, current;
while ((current = getchar()) != EOF) {
switch (mode) {
case single: {
if (last != '\\' && (current == '\n' || current == '\r')) {
putchar(current);
current = 0;
mode = literal;
}
} break;
case multiple: {
if (last == '*' && current == '/') {
current = 0;
mode = literal;
}
} break;
case string: {
if (last == '\\') {
putchar(last);
putchar(current);
} else if (current != '\\') {
putchar(current);
if (current == '"') {
mode = literal;
}
}
} break;
default: {
if (last == '/') {
if (current == '/') {
mode = single;
} else if (current == '*') {
mode = multiple;
} else {
putchar(last);
putchar(current);
}
} else if (current != '/') {
putchar(current);
if (current == '"') {
mode = string;
}
}
} break;
}
last = current;
}
return 0;
}
測試代碼
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
// not show\
not show\
not show
// not show
/* not show */
int is; // not show
int/* not show */ ms; /* not show */
double ds; // not show\
not show\
not show
double dm; /* ...
not show
not show */ float fs; /**
* now show
*/
float/**/ fm;
char cs[] = "aaa // /***/";
char cm1[] = /* not show */"hello*/";
char cm2[] = "/*redraiment"/* not show */;
/* printf("http://///"); */
return EXIT_SUCCESS;
}
處理后的代碼
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
int is;
int ms;
double ds;
double dm; float fs;
float fm;
char cs[] = "aaa // /***/";
char cm1[] = "hello*/";
char cm2[] = "/*redraiment";
return EXIT_SUCCESS;
}
相關(guān)文章
C語言系統(tǒng)日期和時(shí)間實(shí)例詳解
我們?cè)趯慍語言程序的時(shí)候,有的時(shí)候會(huì)用到讀取本機(jī)的時(shí)間和日期,下面這篇文章主要給大家介紹了關(guān)于C語言系統(tǒng)日期和時(shí)間的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06
在C++中實(shí)現(xiàn)aligned_malloc的方法
這篇文章主要介紹了在C++中實(shí)現(xiàn)aligned_malloc的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
詳解C語言中的rename()函數(shù)和remove()函數(shù)的使用方法
這篇文章主要介紹了詳解C語言中的rename()函數(shù)和remove()函數(shù)的使用方法,是C語言入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09
C程序函數(shù)調(diào)用&系統(tǒng)調(diào)用
這篇文章主要介紹了C程序函數(shù)調(diào)用&系統(tǒng)調(diào)用,需要的朋友可以參考下2016-09-09

