[已解决] 编写解析代码是一个陷阱。包含15个空格的行将包含15个单词。空行也算作一个单词。回到弯曲和野牛为我。
#include <stdio.h>
#include <stdlib.h>
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:〜/源极/ bashcrypt&GT; wc foo.sh
5 13 85 foo.sh
ojblass @ Linux的rjxl:〜/源极/ bashcrypt&GT; a.out foo.sh
字符:85,字词:14,行:5。
答案 0 :(得分:3)
你的算法错了。如果你在测试文件中连续有2个空白字符,那么单词的计数器将增加两次,但它应该只增加一次。
解决方案是记住最后一个字符读取。如果读取的字符是特殊字符(空白,换行,......),而前一个字符是字母数字,那么您可以增加单词的计数器。
答案 1 :(得分:2)
即使是一个空行,你也算作一个单词。