實現(xiàn)去除c語言注釋的小工具
去除C代碼中的注釋,
1. 單行注釋//;
2. 多行注釋/**/;
3. 單行注釋以“\”結尾則下一行也為注釋;
4. 字符串中的注釋不處理。
說是C語言,但其實所有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;
}
相關文章
C++實現(xiàn)LeetCode(119.楊輝三角之二)
這篇文章主要介紹了C++實現(xiàn)LeetCode(119.楊輝三角之二),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-07-07Qt創(chuàng)建SQlite數(shù)據(jù)庫的示例代碼
本文主要介紹了Qt創(chuàng)建SQlite數(shù)據(jù)庫的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05