前言
这个题目有点不严谨,数字也算是单词,我以为这个,Let’s go to room 209.
5个单词是let us go to room。。。。是我戏太多了吗😐
正文
题目
本题目要求编写程序统计一行字符中单词的个数。所谓“单词”是指连续不含空格的字符串,各单词之间用空格分隔,空格数可以是多个。
输入样例:
Let’s go to room 209.
输出样例:
5
代码一(正确)
#include <stdio.h>
int main(){
int wold=0,state=0; /*单词开始标志,1表示单词开始,0表示单词结束*/
int c;
while((c=getchar())!='\n'){
if(c==' '){
state=0;
}
else if(state==0){//输入字母
state=1;
wold++;
}
}
printf("%d",wold);
}
代码二(有错)
看我之前的代码,用了isalpha
#include <stdio.h>
#include <ctype.h>
int main(){
int wold=0,state=0;//state表示是否在单词中,0为不在,1为在
int c;
while((c=getchar())!=EOF){
if(c==' '||c=='\''){
state=0;
}
else if(state==0&&isalpha(c)){//输入字母
state=1;
wold++;
}
}
printf("%d",wold);
}
这个错我想了好久没想明白,然后就把上面的代码二改成代码一就通过了,令人头大😂