为什么我用一个词来执行wc?

[解决]编写解析代码是一个陷阱。 一个有15个空格的行将有15个单词。 空行也算作一个单词。 回到弯曲和野牛为我。

#include  #include  int main(int argc, char *argv[]) { FILE *fp = NULL; int iChars =0, iWords =0, iLines =0; int ch; /* if there is a command line arg, then try to open it as the file otherwise, use stdin */ fp = stdin; if (argc == 2) { fp = fopen(argv[1],"r"); if (fp == NULL) { fprintf(stderr,"Unable to open file %s. Exiting.\n",argv[1]); exit(1); } } /* read until the end of file, counting chars, words, lines */ while ((ch = fgetc(fp)) != EOF) { if (ch == '\n') { iWords++; iLines++; } if (ch == '\t' || ch == ' ') { iWords++; } iChars++; } /* all done. If the input file was not stdin, close it*/ if (fp != stdin) { fclose(fp); } printf("chars: %d,\twords: %d,\tlines: %d.\n",iChars,iWords,iLines); } 

测试数据foo.sh

 #!/home/ojblass/source/bashcrypt/a.out This is line 1 This is line 2 This is line 3 

ojblass @ linux-rjxl:〜/ source / bashcrypt> wc foo.sh

5 13 85 foo.sh

ojblass @ linux-rjxl:〜/ source / bashcrypt> a.out foo.sh

字数 :85, 字数:14,行数:5。

即使是一个空行,你也算作一个单词。

你的算法错了。 如果在测试文件中连续有2个空白字符,则单词的计数器将递增两次,但它应仅递增一次。

解决方案是记住最后一个字符读取。 如果读取的字符是特殊字符(空白,新行,…),而前一个字符是字母数字,则增加单词的计数器。