尝试删除空格时C代码出错

这段代码是词法分析器的基础,它执行从源文件中删除空格的基本操作,并将其重写为另一个文件,每个单词在不同的行中。 但我无法理解为什么文件lext.txt没有得到更新?

#include /* this is a lexer which recognizes constants , variables ,symbols, identifiers , functions , comments and also header files . It stores the lexemes in 3 different files . One file contains all the headers and the comments . Another file will contain all the variables , another will contain all the symbols. */ int main() { int i; char a,b[20],c; FILE *fp1,*fp2; fp1=fopen("source.txt","r"); //the source file is opened in read only mode which will passed through the lexer fp2=fopen("lext.txt","w"); //now lets remove all the white spaces and store the rest of the words in a file if(fp1==NULL) { perror("failed to open source.txt"); //return EXIT_FAILURE; } i=0; while(!feof(fp1)) { a=fgetc(fp1); if(a!="") { b[i]=a; printf("hello"); } else { b[i]='\0'; fprintf(fp2, "%.20s\n", b); i=0; continue; } i=i+1; /*Switch(a) { case EOF :return eof; case '+':sym=sym+1; case '-':sym=sym+1; case '*':sym=sym+1; case '/':sym=sym+1; case '%':sym=sym+1; case ' */ } return 0; } 

只有在此条件失败时才写入文件:

 if(a!="") // incorrect comparison..warning: comparison between pointer and integer 

从来没有这样做,你永远不会去else地方。

将测试更改为:

 if(a!=' ') 

编辑:

到达文件末尾时,只需终止程序而不写入数组中的内容b 。 所以在while循环之后需要另一个fprintf

 } // end of while loop. b[i]='\0'; fprintf(fp2, "%.20s\n", b); 

好吧,这里的代码经过测试,工作正常:)

 while(1) { a=fgetc(fp1); if(feof(fp1)) break; if(a!=' ') b[i++]=a; else { b[i]='\0'; fprintf(fp2, "%.20s\n", b); i=0; } } b[i]='\0'; fprintf(fp2, "%.20s\n", b); 

你忘了冲! (除其他外……):- P


if(a!=”)

//将待处理数据写入文件

fflush();

//释放文件指针

FCLOSE(FP2);

这是完整的代码:

 #include /* this is a lexer which recognizes constants , variables ,symbols, identifiers , functions , comments and also header files . It stores the lexemes in 3 different files . One file contains all the headers and the comments . Another file will contain all the variables , another will contain all the symbols. */ int main() { int i; char a,b[20],c; FILE *fp1,*fp2; fp1=fopen("source.txt","r"); //the source file is opened in read only mode which will passed through the lexer fp2=fopen("lext.txt","w"); //now lets remove all the white spaces and store the rest of the words in a file if(fp1==NULL) { perror("failed to open source.txt"); //return EXIT_FAILURE; } i=0; while(!feof(fp1)) { a=fgetc(fp1); if(a!=' ') { b[i]=a; printf("hello"); } else { b[i]='\0'; fprintf(fp2, "%.20s\n", b); i=0; } i=i+1; //writes pending data to file fprintf(fp2, "%.20s\n", b); fflush(); //Releases file-pointer fclose(fp2); /*Switch(a) { case EOF :return eof; case '+':sym=sym+1; case '-':sym=sym+1; case '*':sym=sym+1; case '/':sym=sym+1; case '%':sym=sym+1; case ' */ } return 0; } 

祝好运!!

CVS @ 2600Hertz