isspace() 不会计算 C 中的空格

isspace() will not count spaces in C

我这里有这个练习题。当我输入一个包含多个空格的句子时,我希望它能告诉我那个数字。但是,它只会说 0 个空格。我犯了一个愚蠢的小错误吗?

#include <stdio.h>
#include <ctype.h>

#define COUNT 40

int main()
{
  char input[COUNT];
  printf("Enter a sentence: ");
  scanf("%s", input);

  int loopCount;
  int spaceCount = 0;

  for(loopCount = 0; loopCount < COUNT; loopCount++)
  {
    if (isspace(input[loopCount]))
    {
      spaceCount++;
      printf("SO MUCH STUFF");
    }
    else{}
  }

  printf("That sentence has %d spaces.", spaceCount);
  return(0);
}

scanf with %s modifier will read one string ( using whitespace to mark end )..

要修复,请使用 fgets

代码

#include <stdio.h>
#include <ctype.h>

#define COUNT 40

int main()
{
  char input[COUNT];
  printf("Enter a sentence: ");

  // read line of string ( or first COUNT characters )
  // this is also a safer alternative for buffer overflow
  fgets(input, COUNT, stdin);

  int loopCount;
  int spaceCount = 0;

  for(loopCount = 0; loopCount < COUNT; loopCount++)
  {
    if (isspace(input[loopCount]))
    {   
      spaceCount++;
    }
  }

  printf("That sentence has %d spaces.\n", spaceCount);
  return 0;
}

输出

$ ./test
Enter a sentence: sentence with spaces
input: sentence with spaces

That sentence has 3 spaces.

@amdixon 说得很对,scanf 只读到空格,所以你通常用 scanf 做这样的事情的方式是用一个 while 循环,但是 fgets 和读入静态分配的数组都是非常不确定的事情。这里的美妙之处在于你可以懒惰到很好的效果。像这样的东西会很好用:

char next = 0;
while (next != '\n')
{
    scanf("%c", &next);
    if (next == ' ')
        spaceCount++;
}