ifstream的特点是,只能识别空格,其他的符号不识别(也可以理解为他把其他的字符当做字母来处理),它一次读入时,将逗号、引号、等等符号和单词都一并读入。
这时我们需要将单词分离出来,有两种特殊情况需要考虑:
hello,world my name 考虑这个,有个逗号,ifstream会将其分割为 hello,world my name 共三个部分。跳到一个新的单词时,i等于0。在hello,world内部时,逗号不是字母。因此可以将这两种特殊的情况考虑进去。
当涉及到排序时,可以定义一个优先级队列priority_queue,定义cmp比较规则,则可以完成排序。
使用chs来保存缓存输入的单词,当需要将chs维护到whale中时,再进行维护。
#include<cstdio>
#include<fstream>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef struct Food {
int frequency;
char word[20];
} Whale[13000];
struct cmp {
bool operator () (const Food a,const Food b) const {
return a.frequency < b.frequency;
}
};
int current=0;
int cur_food=0;
char chs[20];
int chs_full = 0;//刚开始chs是空的
Whale whale;
int save(char *chs) {
int flag=false;
for(int j=0; j<cur_food; j++) { //比对一下,看看这个单词是否已经存在
if(strcmp(whale[j].word,chs) == 0) { //如果之前有这个单词
whale[j].frequency++;
flag=true;
break;
}
}
if(!flag) { //如果之前没有这个单词
strcpy(whale[cur_food].word,chs);//将chs的内容复制给...
whale[cur_food].frequency=1;
cur_food++;
}
for(int i=0; i<20; i++) {
chs[i]=0;
}
chs_full=0;
current=0;//便于从第0个下标开始装入
}
int main() {
ifstream infile("data.txt");
ofstream outfile("out.txt");
if(!infile) {
printf("cannot open!\n");
return 0;
}
while(infile) {
string temp;
infile>>temp;
if(chs_full) { //如果chs是满的(适用于跳到一个新区域处,区域与区域之间使用空格作为分隔符,这时ifstream默认的)
save(chs);
}
for(int i=0; i<temp.length(); i++) {
if(isalpha(temp[i])) {//如果是字母
chs[current++]=temp[i];//构造chs
chs_full=1;//表明chs的状态已经是非空了,这里用来便于表示chs中有内容了。
} else {//碰到特殊字符了(不是我们想要的字母) ,这时有两种情况
if(chs_full) {//第一种情况 hello,world 这种情况,之前在chs中已经存入了hello
save(chs);
} else {
/*
第二种情况,例如 hello "world" 这种情况是从hello跳过来的,
由于跳到一个新区域时,在第51行代码处已经进行了检查,所以已经完成了存入,这时不必处理。
*/
continue;//不必处理
}
}
}
}
priority_queue<int,vector<Food>,cmp> pq;//定义优先级队列
for(int i=0; i<cur_food; i++) {
pq.push(whale[i]);
}
int len = pq.size();
for(int i=0; i<len; i++) {
outfile<<pq.top().word<<" "<<pq.top().frequency<<endl;
pq.pop();
}
return 0;
}