c语言统计句子单词个数(不算end)读以end为结尾的句子 要求不能有gets要用scanf一个一个词读 还有要用字符串比较strcmp来判断end在哪里

img

img


c语言统计句子单词个数(不算end)读以end为结尾的句子 要求不能有gets要用scanf一个一个词读 还有要用字符串比较strcmp来判断end在哪里 我只会用gets写

#include <stdio.h>
#include <string.h>

int main() {
  char buffer[255];
  int count = 0;
  while (scanf("%s", buffer) == 1 && strcmp(buffer, "End") != 0)
    count++;
  printf("%d\n", count);
  return 0;
}

那就用scanf输入好了。检查输入的单词是否End,如果是,则结束;否则单词数加1

#include <stdio.h>
#include <string.h>
int main()
{
    char s[1000] = {0};
    int count = 0;
    while(1)
    {
        scanf("%s",s);
        if(strcmp(s,"End") == 0)
            break;
        count++;
    }
    printf("%d",count);
    return 0;
}

输入只包含字母和空格,用scanf("%s")一直读取,并统计,直到读入End为止。

int main()
{
    char s[100];
    int count = 0;
    while (1)
    {
        scanf("%s", s);
        if (strcmp(s, "End"))
            count++;
        else
            break;
    }
    printf("%d\n", count);

    return 0;
}

供参考:

#include <stdio.h>
#include <string.h>
int main()
{
    char str[64];
    int  words = 0;
    while (scanf("%s", str) == 1 && strcmp(str,"End") != 0)
         words++;
    printf("%d",words);
    return 0;
}