单词统计问题 C或C++解决

[题目描述]统计若干行英文中单词的个数和每个单词出现的次数。 [输入]若干行英语。 [输出]单词数量及每个单词出现的次数。

#include
#include
struct word
{
char c[30];
int n;
}w[10000];

main()
{
FILE *fp;
char b[30],ch;
int i=0,m=1,j=0,k=0,t=0,flag=0;
fp=fopen("d://a.txt","r+");
while((ch=fgetc(fp))!=EOF)
{
if('A'<=ch&&ch<='Z') ch=ch+32;

if('a'<=ch && ch<='z')
{b[i]=ch;i++;flag=1;}
else
{
if(ch=='-'&&(ch=fgetc(fp))=='\n')
{
flag=0;
}

else
{
if(flag==1)
{ b[i]='\0';i=0;flag=0;m=0;
for(j=0;j<k;j++)
{
if(strcmp(b,w[j].c)==0)
{m=1;break;}
}
if(m) w[j].n++;
else
{w[k].n=1;strcpy(w[k].c,b);k++;}
}
}

if('A'<=ch && ch<='Z') ch+=32;
if('a'<=ch && ch<='z')
{b[i]=ch;i++;flag=1;}
}
}
// printf("%d\n",k);
for(i=0;i printf("\n");
for(i=0;i {
t=0;
while(w[t].n==0) t++;
for(j=1;j {
if(w[j].n>w[t].n) t=j;
else
if(w[j].n==w[t].n)
{
if(strcmp(w[j].c,w[t].c)<0)
t=j;
}
}
printf("%s %d\n",w[t].c,w[t].n);
w[t].n=0;
}
return 0;
}

代码显示有问题,参考:http://blog.sina.com.cn/s/blog_6ade50270100z9sl.html

你需要定义地更清楚一些。比如英文为friendship,你期望的结果是什么?一个单词?还是很多个单词呢?你有英文单词库吗?

你打开文件有问题吧。fp=fopen("d://a.txt","r+");这里的斜杠用反了吧。应该是\,由于字符'\'是转义符,所以要写两遍才能表示真正的斜杠。你这里写错误,自然fopen打不开文件,fp就是空的了。但你的代码根本没有判断fopen的返回值,然后直接就进行操作,必死无疑。

#include
#include
using namespace std;
int main()
{
char b[26];
int c[26]={0},i,j,m=1,k;
string a;
cin>>a;
b[0]=a[0];
for(i=0;i {
k=0;
for(j=0;j {
if(a[i]==b[j])
{
c[j]++;break;
}
else if(a[i]!=b[j]&&j==m-1)
k=1;
}
if(k==1)
{
b[m]=a[i];
c[m]++;
m++;
}
} cout for(i=0;i if(c[i]>0)
cout<<b[i]<<" "<<c[i]<<endl;
return 0;
}

#include
#include
#include
using namespace std;
struct Word
{
string word;
int count;
Word next;
}*hand;
void addWord(string word);
void WordCount(char
FileName);
int main()
{
hand=new Word;
hand->next=NULL;
cout<<"请输入文件路径"< char a[50];
cin>>a;
WordCount(a);
return 0;
}

void WordCount(char* FileName)
{
ifstream fin;
char c;
string word;
fin.open(FileName,ios::in);
if(!fin.is_open())
{
cout<<"File open error!"< }
while(!fin.eof())
{
fin.get(c);
if(c!=' ' && c!=',' && c!='.' && c!='!' && c!='?' && c!=';' && c!='\"' && c!='\'')
{
word+=c;
}
else
{
addWord(word);
word="";
}
}
fin.close();
Word *temp=hand;
while (temp->next!=NULL)
{
temp=temp->next;
cout<count<<" "<word<<endl;
}

}

void addWord(string word)
{
bool isNew=true;
Word *temp;
// if(hand==NULL)
// {
// hand=new Word;
// hand->next=NULL;
// }
temp=hand;
while(temp->next!= NULL)
{
temp=temp->next;
if(temp->word == word)
{
temp->count++;
isNew=false;
break;
}
}
if(isNew)
{
Word * newWord=new Word;
newWord->count=1;
newWord->word=word;
newWord->next=NULL;
temp->next=newWord;
}
}

map<string,int>
直接桶排