注册 登录
编程论坛 C语言论坛

用getc 和putc 复制一个程序代码到另一个文本中时怎么去掉//后面的部分

清风幽然 发布于 2019-10-09 21:11, 1660 次点击
题目要求只复制代码,但要去掉 //后面的部分,这是题目:
Write a program that reads a file containing a C program and outputs the program
to another file with all the // comments removed.


这是我写的,但不知道要怎么跳过//后面到另一行
#include <stdio.h>
int main (){
 char c;
 FILE *in= fopen ("a.txt","r");
 FILE *out =fopen ("b.txt","w");
 while ((c=getc(in)) !=EOF )
 if (c== '/') "\n";
  putc(c,out);
  fclose(in); fclose(out);  }


比如复制
aaaaa //bbbbb
ccccc
到另一个txt文本里,只保留
aaaaa
ccccc




[此贴子已经被作者于2019-10-9 21:13编辑过]

2 回复
#2
rjsp2019-10-10 09:41
代码要排版一下,你自己看得不难受吗?

程序代码:
#include <stdio.h>

int main( void )
{
    FILE* in = fopen( "a.txt", "r" );
    if( !in )
    {
        puts( "[error] failed to open file \"a.txt\"" );
        return 1;
    }

    FILE* out = fopen( "b.txt", "w" );
    if( !out )
    {
        fclose( in );
        puts( "[error] failed to open file \"b.txt\"" );
        return 2;
    }

    int state = 0; // 状态1表示遇到第一个斜杠,状态2表示已遇到两个斜杠,状态0表示其它情况
    for( int ch; ch=getc(in), ch!=EOF; )
    {
        if( ch == '\n' )
        {
            if( state == 1 )
                putc( '/', out );
            state = 0;
            putc( ch, out );
        }
        else if( state == 2 )
        {
        }
        else if( ch=='/' && state==1 )
        {
            state = 2;
        }
        else if( ch == '/' )
        {
            state = 1;
        }
        else
        {
            if( state == 1 )
                putc( '/', out );
            state = 0;
            putc( ch, out );
        }
    }

    if( ferror(in) )
    {
        fclose( out );
        fclose( in );
        puts( "[error] failed to read file \"a.txt\"" );
        return 3;
    }
    if( ferror(out) )
    {
        fclose( out );
        fclose( in );
        puts( "[error] failed to write file \"b.txt\"" );
        return 4;
    }

    fclose( out );
    fclose( in );
    return 0;
}

#3
清风幽然2019-10-10 16:53
回复 2楼 rjsp
感谢解答!
1