为什么此程序删除所有评论无效?

时间:2018-06-27 04:28:39

标签: c arrays

这是我的21次试用,实际上我找不到我应该在哪里搜索,以下代码是删除单个注释行 我正在使用缓冲区收集所有数据,然后尝试对它们进行过滤,但我怀疑if语句内的行

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

但是直到现在我都找不到区别 这就是整个代码

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

我需要帮助

1 个答案:

答案 0 :(得分:1)

您未输入的字符串用一堆'\0' nul-characters )初始化,该信号表示字符串的结尾。您将忽略输入字符串的注释位置,并留下一堆'\0'

一种解决方案是创建一个特定的计数器,以避免在未输入的字符串中留下垃圾:

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