mohamed tarek
mohamed tarek

Reputation: 125

why this program to remove all comments doesn't worked?

this is my 21 trial really i can't find where should i search , the following code is to remove single comment line i'm using buffer to collect all data then i tried to filer them but i suspect on line inside if statement

 if(arr[pos] == '/' &&  arr[pos+1] == '/')

but i can't find difference till now this is the whole code

#define         MAXSIZE         200
#define         ON              1
#define         OFF             0

char uncomentedBuffer[MAXSIZE];
char Buffer[MAXSIZE];
char comment[MAXSIZE];
void uncommen(char *arr);
//int getLine(char *arr, int lim);
int main(void)
{
    int c, pos = 0;
    while((c = getchar()) != EOF)
    {
        Buffer[pos] = c;
        pos++;
    }
    uncommen(Buffer);
    printf("%s",uncomentedBuffer);
    return 0;
}

void uncommen(char *arr)
{
    int pos = 0 ,nBS = 0, nAS = 0 ,scomment = OFF, bcomment = OFF;
    while(pos <= MAXSIZE )
    {
        if(arr[pos] == '/' &&  arr[pos+1] == '/')
        {
            scomment = ON;
            while(scomment == ON && arr[pos] != '\n')
            {
                pos++;
            }
            scomment = OFF;
        }
        uncomentedBuffer[pos] = arr[pos];
        pos++;
    }
}

i need help

Upvotes: 1

Views: 85

Answers (1)

Hugo Sartori
Hugo Sartori

Reputation: 570

Your uncomented string is initialized with a bunch of '\0' (nul-characters), which signals the end of the string. Your are ignoring a commented position of the input string, and leaving a bunch of '\0' behind.

A solution would be to create a specific counter to avoid leaving trash in the uncomented string:

void uncommen(char *arr) 
{
    int pos = 0, auxPos = 0 ,nBS = 0, nAS = 0 ,scomment = OFF, bcomment = OFF;
    while(pos <= MAXSIZE )
    {
        if(arr[pos] == '/' &&  arr[pos+1] == '/')
        {
            scomment = ON;
            while(scomment == ON && arr[pos] != '\n')
            {
                pos++;
            }
            scomment = OFF;
        }
        uncomentedBuffer[auxPos] = arr[pos];
        pos++;
        auxPos++;
    }
}

Upvotes: 1

Related Questions