一、统计文件单词数量(文件操作)
目的是为了统计txt文档中,单词数量
方案是 状态机
定义两状态,1:在字符中(IN) 2.在字符外(OUT)
因此只需要, OUT->IN的过程,即单词数量+1。默认初始化状态为OUT
(算法还需要严密,比如遇到can’t,换行可能会加-来表示换行)
#include<stdio.h> #include<iostream> using namespace std; #define OUT 0 #define IN 1 #define INIT OUT int count_word(char* filename){ int status=INIT; FILE *fp=fopen(filename,"r"); if(fp==NULL) return -1; char c; //只要统计由OUT变为IN的次数 int word=0; while((c=fgetc(fp))!=EOF){ if(!isalpha(c)){ status=OUT; } else if(OUT==status){ status=IN; word++; } } return word; } int main(int argc,char *argv[]){ if(argc<2) return -1; printf("word:%d\n",count_word(argv[1])); }
shell中进行g++编译和运行
g++ test.cpp -o test ./test a.txt
二、通讯录