统计单词数?
哪位大哥看一下这段统计单词的小程序哪出错了?怎么输入时不识别"空格"?谢谢!程序代码:
#include<stdio.h>
#include<stdbool.h>
int main(void)
{
char str[50];
int count;
int word(char *);
printf("please input a sentence:\n");
scanf("%s",str);
count=word(str);
printf("this sentense has %d words",count);
getch();
return 0;
}
int word(char *p)
{
int count=0;
bool b=true;
char c;
while(p&&*p!='\0')
{
c=*p;
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
{
if(b)
{
count++;
b=false;
}
}
else
{
b=true;
}
p++;
}
return count;
}
#include<stdbool.h>
int main(void)
{
char str[50];
int count;
int word(char *);
printf("please input a sentence:\n");
scanf("%s",str);
count=word(str);
printf("this sentense has %d words",count);
getch();
return 0;
}
int word(char *p)
{
int count=0;
bool b=true;
char c;
while(p&&*p!='\0')
{
c=*p;
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
{
if(b)
{
count++;
b=false;
}
}
else
{
b=true;
}
p++;
}
return count;
}
哪里出错了,好像不识别空格,其他的能行?
[[it] 本帖最后由 zhufeifei 于 2008-3-27 21:55 编辑 [/it]]
----------------解决方案--------------------------------------------------------
int len = strlen(text);
for(int i = 0; i < len; i++)
{
if(text[i] == ' ')
count++;
}
//count就是空格数了
----------------解决方案--------------------------------------------------------
自己解决了,scanf()函数改为scanf("[^\n]",str),因为scanf()函数遇到终端输入"空格","Tab","Enter"就结束接受输入!
----------------解决方案--------------------------------------------------------