|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
以下代码的功能:输入一个句子,输出其中的单词个数,每个单词之间以空格连接。
#include <stdio.h>
#define N 200
void cal(char str[]);
int main()
{
char str[N] /*= {'0'}*/ ;
printf("please input sentence:\n");
gets(str);
cal(str);
return 0;
}
void cal(char str[])
{
int i = 0,k;
for (k = 0; str[i] != '\0'; k++)
{
for (; str[i] != '\ ' && str[i] != '\0'; i++);
i++;
}
printf("there are %d words\n",k);
}
问题出在注释的位置。
假如我加上注释,那么输入回车,输出0;输入N个空格,输出N;但是输入1个单词时,会输出4,输入2个单词,输出为5(多了3个单词)。
假如我取消注释,即给数组的第一个元素初始化,输出结果就正常了。
来个大神看看这什么情况 0.0
- #include <stdio.h>
- int print(int*);
- void cal(char str[])
- {
- int i = 0,k;
- for (k=0;str[k]!='\0';k++)
- {
- if (str[k]=='\ ')
- {
- i++;
- }
- }
- i++;
- printf("there are %d words\n",i);
- }
- int main()
- {
- char str[100];
- printf("please input sentence:\n");
- gets(str);
- cal(str);
- return 0;
- }
复制代码
|
|