[已解决]编写解析代码是一个陷阱。一行15个空格将有15个单词。空行也算作单词。回到flex和bison。
#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:~/source/bashcrypt>
世界杯足球赛
51385福斯
ojblass@linux rjxl:~/source/bashcrypt>
外卖
字符:85,单词:14,行:5。
最佳答案
即使是空行,您也可以将其作为一个字来计算。
关于c - 为什么我的wc实现一言不发?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/739596/