Implement a small tool to remove c language comments

  • 2020-04-02 02:11:14
  • OfStack

Remove comments from C code,
1. Single-line comment //;
2. Multi-line comments /**/;
3. Single-line comments ending with "\" and the next line is also a comment;
4. Comments in strings are not processed.
It says C, but all C languages work, like Java.


Gadget: remove C language comments  


#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;
}

The test code


#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
// not show
not show
not show
// not show

    int is; // not show
    int ms; 
    double ds; // not show
    not show
    not show
    double dm;  float fs; 
    float/**/ fm;
    char cs[] = "aaa // ";
    char cm1[] = "hello*/";
    char cm2[] = "/*redraiment";
    /* printf("/////"); */
    return EXIT_SUCCESS;
}

Processed code


#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;
}


Related articles: