计数单词个数小程序中的错误

#include <stdio.h>
int wordcnt (const char *str);
int main (void)
{
char str[20] = "  b cde cd  ef ";
printf ("%d\n", wordcnt (str));
return 0;
}
int wordcnt (const char *str)
{
int cnt = 0;
int flag = 0;//空格则flag标记为0,字符为1
while (*str)
{
if ((!isspace (*str)) && (flag == 0))
{
cnt++;
flag = 1;
}
else if (isspace (*str))
flag = 0;
str++;
}
return cnt;
}
其中一个小错误,就是while (isspace (*str++));一句。
本来的目的是跳过开头的空格,其实仔细考虑后是不需要的。
而且如果处理的字符串中第一个不是空白的话,会因为跳过第一个字符而出错。
解决方法是直接去掉这一行。

原文地址:https://www.cnblogs.com/liujiahi/p/2196395.html