Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #define STATE_OUT 0
- #define STATE_IN 1
- void remove_comments();
- int main()
- {
- remove_comments();
- return 0;
- }
- void remove_comments()
- {
- // Variable to hold each character read from the input
- int ch;
- // Variables to keep track of whether we're currently inside a comment, a quote, or a line comment
- int comment_state = STATE_OUT;
- int quote_state = STATE_OUT;
- int line_comment_state = STATE_OUT;
- // Variable to remember the last character we saw
- int last_char = 0;
- // Loop over each character in the input until we reach the end of the input
- while ((ch = getchar()) != EOF) {
- // If the character is a quote, and we're not inside a comment or line comment, toggle the quote state
- if (ch == '"' && last_char != '\\' && comment_state == STATE_OUT && line_comment_state == STATE_OUT)
- {
- quote_state = (quote_state == STATE_OUT) ? STATE_IN : STATE_OUT;
- }
- // If the character is a '/', and the last character was also a '/', and we're not inside a comment or quote, enter line comment state
- else if (ch == '/' && last_char == '/' && comment_state == STATE_OUT && quote_state == STATE_OUT)
- {
- line_comment_state = STATE_IN;
- }
- // If the character is a '*', and the last character was a '/', and we're not inside a line comment or quote, enter comment state
- else if (ch == '*' && last_char == '/' && line_comment_state == STATE_OUT && quote_state == STATE_OUT)
- {
- comment_state = STATE_IN;
- }
- // If the character is a '/', and the last character was a '*', and we're inside a comment, leave comment state
- else if (ch == '/' && last_char == '*' && comment_state == STATE_IN)
- {
- comment_state = STATE_OUT;
- ch = 0; // Ensures the '/' isn't printed after a '*/'
- }
- // If the character is a newline, and we're inside a line comment, leave line comment state
- else if (ch == '\n' && line_comment_state == STATE_IN)
- {
- line_comment_state = STATE_OUT;
- }
- // If we're inside a quote, or we're not inside a comment or line comment, print the character
- if (comment_state == STATE_OUT && line_comment_state == STATE_OUT && quote_state == STATE_IN)
- {
- putchar(ch);
- }
- else if (comment_state == STATE_OUT && line_comment_state == STATE_OUT && quote_state == STATE_OUT)
- {
- // If we're not just starting a comment or line comment, print the last character
- if ((ch != '/' && last_char != '/') || (ch != '*' && last_char != '/'))
- {
- if (last_char) putchar(last_char);
- }
- }
- // Update last_char to the current character
- last_char = ch;
- }
- // After we've processed all the input, if there's a last character that we didn't print yet, print it now
- if (last_char) putchar(last_char);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement