统计文件中单词个数,并输出不同单词的个数(下面是我自己写的程序,希望大家帮忙看一下那个地方有错误)
#include<iostream>
#include<fstream>
#include<string>
#include<set>
using namespace std;
int main()
{
ifstream infile("data.txt");
set<char[20]> sstr; //存储不同单词
int i=0; //单词的总个数
int k=0; //c[k];
char c=' '; //当前读入的字符
char prec=' '; //前一个字符
char word[20]; //单词
while(infile>>c) //文件结束时结束循环
{
if(c==' ')
{continue;
prec=c;
k=0;
sstr.insert(word);
}
else
if (prec!=' ') {
i++;
prec=c;
word[k++]=c;
}
}
cout<<endl;
cout << "单词总数:" << i << endl;
cout << "不同单词数目:" << sstr.size() << endl;
cout << "回车键结束...";
return 0;
}
[解决办法]
楼主要的功能,相对来说,用map实现会更好一些。
#include <iostream>#include <map>#include <fstream>#include <string>using namespace std;int main(){ map<string,int> myMap; ifstream infile("data.txt"); string tmp; int i = 0; while(infile>>tmp) { myMap[tmp]++; i++; } cout << "count of word: " << i << endl; cout << "count of diff word: " << myMap.size() << endl; return 0;}
[解决办法]
额。。。我的错。用set够了。
#include <iostream>#include <set>#include <fstream>#include <string>using namespace std;int main(){ set<string> mySet; ifstream infile("data.txt"); string tmp; int i = 0; while(infile>>tmp) { mySet.insert(tmp); i++; } cout << "count of word: " << i << endl; cout << "count of diff word: " << mySet.size() << endl; return 0;}