Sou*_*aha 1 c arrays fgets strcat
我正在用C编写一个程序来计算句子中的空格数.但我还没有设法让它正常工作.如果我输入类似Hello world 1234的内容,当输出预期为5时,我得到的输出是3,
我的代码是:
//Program to count number of words in a given Sentence
#include <stdio.h>
#include <string.h>
int main()
{
char sent[100];
char sentence[] = {' ', '\0'};
printf("\nEnter a sentence :\n");
gets(sent);
strcat(sentence, sent);
int l = strlen(sentence), i = 0, count = 0, countCh = 0;
printf("%d", l);
char ch, ch1;
for (i = 0; i < (l-1); i++)
{
ch = sentence[i];
if (ch == ' ')
{
ch1 = sentence[i+1];
if (((ch1 >= 'A') && (ch1 <= 'Z'))||((ch1 >= 'a') && (ch1 <= 'z')))
count++;
}
}
printf("\nNo of words is : %d", count);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我在Java中使用了相同的逻辑,它运行良好.有人可以解释什么是错的吗?
代码中的问题与定义有关sentence.当您省略数组维度并初始化它时,数组的大小将由初始化程序的长度决定.
引述手册页的strcat()
该
strcat()函数将src字符串附加到dest字符串,覆盖结尾处的终止空字节('\ 0')dest,然后添加一个终止空字节.该字符串可能不重叠,且dest字符串必须有结果了足够的空间.如果dest不够大,程序行为是不可预测的;
也就是说,程序将调用未定义的行为.
这样一来,sentence它的内存肯定比预期的要少.而且,那里strcat()根本不需要.
正确的方法是
sentence一个适当的维度,例如char sentence[MAXSIZE] = {0};,在哪里MAXSIZE将是一个具有您选择的大小的MACRO.fgets()读取用户输入.isspace()(from ctype.h)来检查输入字符串中是否存在空格.