there are no compile-time errors or warning. it runs but it does not
do what it is supposed to.
WANTED: to print the "input C programme" with all comments removed.
GOT: does not print anything.
-------- PROGRAMME -----------
/* K&R2: exercise 1-23
STATEMENT:
write aprogramme to remove all comments from a C programme
dont forget to handle quoted strings and character constants properly.
METHOD:
1.) this programme gets its input a line at a time. it copies all the
lines (full input) into a characters array.
2.) we then call a function "remove_comments" which removes all the
comments from the input.
3.) we then print the "array" which now does not contain any comments.
*/
#include<stdio.h>
#define MAXLENGTH 30000
int getline(char arr[]);
void remove_comments(char arr[]);
int main()
{
int i = 0;
char arr[MAXLENGTH];
/* initialising array */
for(i = 0; i < MAXLENGTH - 1; ++i)
arr[i] = 0;
while(getline(arr))
;
remove_comments(arr);
printf("-------------------------\n");
printf("%s\n", arr);
return 0;
}
int getline(char arr[])
{
int c = 0;
int i = 0;
for(i = 0; i < MAXLENGTH - 1 && (c = getchar()) != EOF && c != '\n';
++i)
arr[i] = c;
if(c == '\n')
arr[i++] = '\n';
arr[i] = '\0';
return i;
}
void remove_comments(char arr[])
{
int i = 0;
int j = 0;
int incomment = 0;
char arr2[MAXLENGTH -1];
for(i=0; i < MAXLENGTH - 1; ++i)
arr2[i] = 0;
for(i=0; arr[i] != '\0'; ++i)
{
if(arr[i] != '"')
{
if(arr[i] == '/' && arr[i+1] == '*')
incomment = 1;
}
if(arr[i] == '*' && arr[i+1] == '/' && arr[i+2] != '"')
incomment = 0;
if(incomment == 0)
arr2[j++] = arr[i];
}
arr2[j] = '\0';
for(i = 0; arr2[i] != '\0'; ++i)
arr[i] = arr2[i];
}
----------- OUTPUT ----------------
[arch@voodo kr2]$ gcc -ansi -pedantic -Wall -Wextra -O ex_1-23.c
[arch@voodo kr2]$ ./a.out
like this
-------------------------
[arch@voodo kr2]$