Моя версия кода для удаления комментариев в файле AC не работает - PullRequest
0 голосов
/ 08 февраля 2019

Ну, я сейчас не думаю о таких проблемах, как

char*s="HELLO WORLD /*ABCD*/";

Моя главная цель - узнать, почему, черт возьми, этот код НИЖЕ не работает, как я хочу, чтобы он был

#include <stdio.h>
int main()
{
    FILE *src=fopen("Program.c","rb");
    if(src==0)
    {
        printf("ERROR OPENING THE SOURCE FILE\n");
        return 0;
    }
    FILE *des=fopen("NewProgram.txt","wb");
    if(des==0)
    {
        printf("ERROR OPENING THE DESTINATION FILE\n");
        return 0;
    }

    char ch;
    while((ch=fgetc(src))!=EOF)
    {
        if(ch=='/')
        {
            ch=fgetc(src);
            if(ch=='/')//single line comment encountered
             {
                 while((ch=fgetc(src))!='\n');//scan till an 'ENTER' is found
                 fputc(ch,des);//adding the '\n' to the file

             }
             else if(ch=='*')//multi-line or documentation encountered
                while((ch=fgetc(src))!='/');//scan till the closing '/' is encountered
             else
             {
                fputc('/',des);
                fputc(ch,des);
             }

        }
        else
            fputc(ch,des);
    }
    return 0;
}

ниже - это Program.c

#include <stdio.h>
int nthNonFibonacci(int n,int a,int b);
//call the function with (n(the desired term),fib1,fib2)
//fib1 and fib2 are 2 and 3 respectively
//they are starting consecutive fibonacci numbers
//0 and 1 avoided as they shall unnecessarily increase stack depth
int main()
{
    int n;//to store the upper limit
    printf("ENTER THE UPPER LIMIT OF NON FIBONACCI SERIES\n");
    scanf("%d",&n);//input of upper limit
    printf("\nTHE SERIES :\n");
    for(int i=1;i<=n;i++)
        printf("%d ",nthNonFibonacci(i,2,3));
    return 0;
}


/** a and b are two consecutive fibonacci numbers
*   (b-a-1) => gives the number of non fibonacci numbers b/w a and b
*   we subtract (b-a-1) from n to make sure that we have logically traversed
*   the  non fibonacci numbers b/w a and b
*   this is done when n-(b-a-1)>0 and also at the same time we update a
*   and b to the next consecutive fibonacci numbers
*   now our base case is when in a pass n-(b-a-1) <=0 which means that
*   our required nth non fibonacci number lies b/w current a and b
*   so in that situation we simply return the LOWER_LIMIT_FIBONACCI(i.e. a)
*   added to current n
*/
int nthNonFibonacci(int n,int a,int b)
{
    if((n-(b-a-1))<=0)
        return (n+a);
    else
        return nthNonFibonacci(n-(b-a-1),b,a+b);
}

, ниже - это NewProgram.txt

#include <stdio.h>
int nthNonFibonacci(int n,int a,int b);




int main()
{
    int n;
    printf("ENTER THE UPPER LIMIT OF NON FIBONACCI SERIES\n");
    scanf("%d",&n);
    printf("\nTHE SERIES :\n");
    for(int i=1;i<=n;i++)
        printf("%d ",nthNonFibonacci(i,2,3));
    return 0;
}


w a and b
*   we subtract (b-a-1) from n to make sure that we have logically traversed
*   the  non fibonacci numbers b/w a and b
*   this is done when n-(b-a-1)>0 and also at the same time we update a
*   and b to the next consecutive fibonacci numbers
*   now our base case is when in a pass n-(b-a-1) <=0 which means that
*   our required nth non fibonacci number lies b/w current a and b
*   so in that situation we simply return the LOWER_LIMIT_FIBONACCI(i.e. a)
*   added to current n
*/
int nthNonFibonacci(int n,int a,int b)
{
    if((n-(b-a-1))<=0)
        return (n+a);
    else
        return nthNonFibonacci(n-(b-a-1),b,a+b);
}

Я также проверил на предмет зависания.Но я не понимаю, почему последний блок else также выполняется в случае документации или многострочных комментариев

Это какое-то неопределенное поведение, через которое я прохожу.

fgetc (int, FILE *) => Я знаю, что работает последовательно, и как только он заставляет указатель файла двигаться вперед, он не должен возвращаться обратно, тогда как происходит ситуация?

1 Ответ

0 голосов
/ 12 марта 2019

Вам необходимо проверить наличие * / и не только / поскольку некоторые из ваших комментариев / сами по себе помечены. Обратите внимание, что ваш код удалил деталь из / ** ..... b /

Учитываяниже приведена модифицированная версия вашего кода, которая реализует проблему.

 #include <stdio.h>
void removeComments();//removes the comments from the file
        //pointed by src
FILE *src,*des;//file pointers for the source and destination
int main()
{
    src=fopen("Program.c","rb");//opening the source program
                //file in read binary mode
    if(src==0)//fopen return NULL if there is error in opening
    {       //file
        printf("ERROR OPENING THE SOURCE FILE\n");
        return 0;
    }
    des=fopen("NewProgram.txt","wb");//opening/creating the
            //destination file in write binary mode
    if(des==0)//fopen returns NULL if there is error
    {
        printf("ERROR OPENING THE DESTINATION FILE\n");
        return 0;
    }
    removeComments();//calls the remove comments function to
        //remove the comments
    fclose(src);//closing the source
    fclose(des);//closing the destination
    return 0;
}//end of main

void removeComments()
{
    int curr,next;//creating the current and next character as
        //int as they might require comparison with EOF i.e.-1
    while((curr=fgetc(src))!=EOF)//the while loop runs till the
    {       //end of file is reached
        if(curr=='/')//probable beginning of a comment
        {
           curr=fgetc(src);//reading the next character from src
           if(curr=='/')//single-line comment encountered
           {
               while((curr=fgetc(src))!='\n');//scan till an Enter is encountered
                fputc(curr,des);//writing the '\n' scanned last
                                    //to the destination file
            }//end of if
            else if(curr=='*')//a multi-line or documentation encountered
            {
                next=fgetc(src);//scaning the next character
                while(!(curr=='*'&&next=='/'))//the loop runs till
                {           //the */ is encountered
                    curr=next;      //moving through the file in turn of
                    next=fgetc(src);//two characters
                }//end of while
            }//end of else if
            else//situation where / was scanned but the next element was not a /
                //because if / was scanned and the next is * then definitely a block comment
                //has started
            {
                fputc('/',des);
                fputc(curr,des);
            }
        }//end of other if
        else if(curr=='"')//handling the string
        {
            fputc(curr,des);//writing the opening " to the file
            while((curr=fgetc(src))!='"')
                    fputc(curr,des);
            fputc(curr,des);//writing the closing " to the file
        }//end of else if
        else//dealing the normal code
            fputc(curr,des);//writing them to the destination file
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...