第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;
}