要求:用户输入一段话,输出每个单词出现的次数
如输入:hello my friend . I miss you , my friend
输出:单词 次数
hello 1
my 2
friend 2
I 1
miss 1
you 1
#include
#include
#include
using namespace std;
int main()
{
string sen;//用来记录用户输入的句子
string word[100];
int a,b;
int times;//用来计相同单词的数目
string::size_type first=0,end=0;
int counter=1;
cout<<"请输入一段话:";
getline(cin,sen);
int i=0;//word数组的下标
//将所有标点符号转化为空格
for(int j = 0;j<sen.size();j++)
{
if(' ' == sen[j] || ',' == sen[j] || '.' == sen[j] || '!' == sen[j] || ';' == sen[j] || '?' == sen[j])
sen[j] = ' ';
}
//用空格作为分隔符将字符串中的单词分隔出来
while(1)
{
if(((end=sen.find(' ',first)) != string::npos)||((end=sen.find(' ',first)) != string::npos)||((end=sen.find(' ',first)) != string::npos))
{
word[i++]=sen.substr(first,end-first);
first=end+1;
counter++;
}
else
break;
}
word[i]=sen.substr(first,sen.size()-first);
cout<<"word"<<setw(13)<<"times"<<endl;
cout<<endl;
//对比字符串函数中单词出现的次数
for(a=0;a<counter-1;a++)
{
times=0;
for(b=0;b<counter;b++)
{
if(word[a] == word[b])
times++;
}
}
for(int k=0;k<counter;k++)
{
cout<<word[k]<<setw(13)<<times<<endl;
}
return 0;
}
我的结果这么是这样啊?
哪错了啊?我实在搞不懂了。。大家帮我看一看。。
那三个include是
#include
#include
#include
刚刚复制的时候没复制上去
iostream
string>
iomanip
程序有根本性的错误,你只有一个time变量,怎么可能保存每个单词出现的次数,起码你需要一个数组吧。
有几个问题:
1.while(1)循环里,如果当前的字符串不是""才把它放入word数组里
2.输出的时候,times应该弄成数组的,楼主是一个数的话,最后输出的所有单词的times都是一样的了。。
3.for(a=0;a<counter;a++)循环的次数,应该都是counter次
4.如果找到了相同的单词,应该把后面的这个单词置为""
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string sen;//用来记录用户输入的句子
string word[100];
int a,b;
int times[100];//用来计相同单词的数目
string::size_type first=0,end=0;
int counter=1;
cout<<"请输入一段话:";
getline(cin,sen);
int i=0;//word数组的下标
//将所有标点符号转化为空格
for(int j = 0;j<sen.size();j++)
{
if(' ' == sen[j] || ',' == sen[j] || '.' == sen[j] || '!' == sen[j] || ';' == sen[j] || '?' == sen[j])
sen[j] = ' ';
}
//用空格作为分隔符将字符串中的单词分隔出来
while(1)
{
if(((end=sen.find(' ',first)) != string::npos)||((end=sen.find(' ',first)) != string::npos)||((end=sen.find(' ',first)) != string::npos))
{
if(sen.substr(first,end-first) != "")
{
word[i++]=sen.substr(first,end-first);
counter++;
}
first=end+1;
}
else
break;
}
word[i]=sen.substr(first,sen.size()-first);
cout<<"word"<<setw(13)<<"times"<<endl;
cout<<endl;
//对比字符串函数中单词出现的次数
for(a=0;a<counter;a++)
{
times[a]=1;
for(b=a+1;b<counter;b++)
{
if(word[a] == word[b])
{
times[a]++;
word[b] = "";
}
}
}
for(int k=0;k<counter;k++)
{
if(word[k] != "")
cout<<word[k]<<setw(13)<<times[k]<<endl;
}
return 0;
}