求解 c++ 输入一句话,求单词的长度和出现次数

c++ 输入一句话,求单词的长度和出现次数、
例如:hot it is a day of
单词长度:1 出现次数:1
单词长度:2 出现次数:3
单词长度:3 出现次数:2

#include<iostream>
using namespace std;

void main()
{
char ch;
int i=0,j=0;
int sum[20]={0}; //初始化数组全部为0
cout<<"please input:"<<endl;
while((ch=getchar())!='\n')
{
//判断是否为空格,即一个单词是否输入完毕,当遇到空格则自动保存到sum[j]数组中,且出现次数加1,j为单词长度
if(!isspace(ch))
j++;
else
{
sum[j]++;
j=0; //一个单词输入完后,将j重置为0,开始下一个单词的输入
}
}
sum[j]=sum[j]+1; //最后一个单词没有空格结尾,则上面循环语句中else分支的sum[j]++不会执行到,所以这里要sum[j]+1
for(i=0;i<20;i++)
{
if(sum[i]!=0)
cout<<"单词长度为"<<i<<" "<<"出现次数为"<<sum[i]<<"次"<<endl;
}
}

要是看不明白就调试在循环语句那设个断点,很容易就明白了
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-11-18
#include<stdio.h>
#include<ctype.h>
#define STOP '|'
int main(void)
{
char c;
char prev;
long n_chars = 0L;
int n_lines = 0;
int n_words = 0;
int p_lines = 0;
int inword = 0;

printf("Enter text to be analyzed( | to be quit):\n ");
prev = '\n';
while((c = getchar()) != STOP)
{
n_chars++;
if (c == '\n')
n_lines++;
if (!isspace(c) && !inword)
{
inword = 1;
n_words++;

}
if(isspace (c) && inword)
inword = 0;
prev = c;
}

if(prev != '\n')
p_lines = 1;
printf("characters = %ld,word = %d,line = %d,",
n_chars,n_words,n_lines);
printf("partial lines = %d\n",p_lines);
return 0;

}
prev 是一个字符变量,用于检查是否到了一行的末尾。 这个例子不是很难,用#define是为了增加程序的可修改性,你可以只看关键的方法部分也就是如何计算单词数和行数。 至于出现的次数,1、你要重新定义一个变量和数组也可以用指针分配空间的方式,将每一个不同的字符都存入数组中,以备以后判断;2、在后面要加一个判断语句,判断目前的字符与以前出现过的字符是否重复,重复就++,否者就继续下一个字符,在这个程序的基础上应该不难。本回答被网友采纳
第2个回答  2010-11-18
/*
楼上的两位,用的是标准的C语言。我看是不符合要求了。。呵呵
额。。。我是基于C++ STL 实现的,不知道是不是满足你要求,有不明白的地方,咱在讨论。。。祝:事业有成!
测试用例:
输入:sun sun xiao liang liang @
*/

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main()
{
typedef pair< map<string,int>::iterator,bool> Point;
typedef pair<string,int> SI_PAIE;
string str;
map<string,int> si_map;
cout<<"input the words:(end with '@')";
while(cin>>str)
{
if(str=="@")
break;
Point pt=si_map.insert(SI_PAIE(str,1));
if(pt.second== false)
(pt.first)->second+=1;
}
map<string,int>::iterator itr=si_map.begin();
for(;itr!=si_map.end();itr++)
cout<<"Word : "<<itr->first<<"; "<< "number : "<<itr->second<<endl;
return 0;
}
第3个回答  2010-11-18
运行了下楼上的程序,有点答非所问。。。。
和楼上比我写的这个程序感觉很基础:不过保证正确~~~
#include"stdio.h"
#include"stdlib.h"

int main()
{ int i,j=0,k=0,x,a[10]={0};
char *str=(char *)malloc(100);//参数酌情更改
gets(str);
for(i=1;*(str+i)!='\0';i++)
{
if(str[i]==' '||str[i+1]=='\0')
{ while(str[i]==' ')++i;
for(x=j;str[x]!='\0'&&str[x]!=' ';++x)++k;
j=i;a[k]++;k=0;}
}
for(i=1;i<10;++i)
{if(a[i]!=0)printf("单词长度:%d 出现次数:%d\n",i,a[i]);}
system("pause");
return 0;
}