Reputation: 41
Ok I have another question for this program we are supposed to take .C file and remove all the comments from it, I have it sort of working but the program seems to get stuck after it removes the first comment. After it removes the first comment it stops saving things after it and i cant figure out why.
Exact book question: Write a program to remove all comments from a C program. Don't forget to handle quoted strings and character constants properly.
I only wrote this program to remove the /* */ comments and if i get it working ill change it to be able to do the // comments as well.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX_BUFFER 5000
#define SPACE ' '
#define TAB '\t'
#define IN 1
#define OUT 0
/* ********************************************************************** */
int main()
{
char arrayPrimary[MAX_BUFFER];
char arraySecondary[MAX_BUFFER];
int i, c, j, size, string;
for(i = 0;(c = getchar()) != EOF && c != '\0'; i++)
{
arrayPrimary[i] = c;
}
arrayPrimary[i] = '\0';
size = i;
string = OUT;
/* ********************************************************************** */
for(i = 0, j = 0; i < size; i++, j++)
{
if((arrayPrimary[i] == '/' && arrayPrimary[i + 1] == '*'))
{
printf("IN\n");
string = IN;
}
else if(string == OUT)
{
arraySecondary[j] = arrayPrimary[i];
}
else if(string == IN && arrayPrimary[i] == '*' && arrayPrimary[i + 1] == '/')
{
printf("OUT\n");
i++;
string = OUT;
}
}
arraySecondary[j] = '\0';
printf("%s", arraySecondary);
return 0;
}
If i input this Codefile i get.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX_BUFFER 5000
#define SPACE ' '
#define TAB '\t'
#define IN 1
#define OUT 0
Upvotes: 2
Views: 610
Reputation: 23058
When you are IN comment area, you should either stop increasing j
or fill something non-'\0'
as j
goes forward. Otherwise, the buffer may be stopped by random '\0'
due to uninitialized arraySecondary
.
My implementation would be removing j++
from the for loop and make the out-of-comment-area statement as follows.
else if(string == OUT)
{
arraySecondary[j++] = arrayPrimary[i];
}
Upvotes: 1