无由頁 2020-03-10 18:18 采纳率: 0%
浏览 1144

PTA一个入门题目:统计一行文本的单词个数,为什么有“空格结尾”错误?

题目:本题目要求编写程序统计一行字符中单词的个数。所谓“单词”是指连续不含空格的字符串,各单词之间用空格分隔,空格数可以是多个。
输入样例:Let's go to room 209.输出样例:5

#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);
}

图片说明

  • 写回答

1条回答 默认 最新

  • upbeat_student 2021-04-26 19:48
    关注

    #include<stdio.h>
    int main(){
        char ch;
        int count=0,t=0;
        //第一次出现字母()单词+1
        while(1){
            ch=getchar();
            if(ch=='\n')break;
            if(ch==' ')t=0;
            if(t==1)continue;
            if(ch!=' '){
                count++;t=1;
            }
        }
        printf("%d",count);
        return 0;
    }

    评论

报告相同问题?