我正在用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;
}
我在Java中使用了相同的逻辑,它运行良好。有人可以解释什么是错的吗?
答案 0 :(得分:5)
代码中的问题与sentence
的定义有关。当你省略数组维度并初始化它时,数组的大小将由初始化程序的长度决定。
引用strcat()
strcat()
函数将src
字符串附加到dest
字符串,覆盖dest
末尾的终止空字节('\ 0'),然后添加一个终止空字节。字符串可能不重叠,和dest
字符串必须有足够的空间用于结果。如果dest
不够大,则程序行为无法预测;
即,程序将调用undefined behavior。
这样,sentence
的内存肯定比预期的要少。此外,strcat()
根本不需要 。
正确的方法是
sentence
,例如char sentence[MAXSIZE] = {0};
,其中MAXSIZE
将是一个具有您选择尺寸的MACRO。fgets()
来阅读用户输入。isspace()
(来自ctype.h
)来检查输入字符串中是否存在空格。答案 1 :(得分:0)
以下
if (((ch1 >= 'A') && (ch1 <= 'Z'))||((ch1 >= 'a') && (ch1 <= 'z')))
count++;
可能应该是
if (ch1 != ' ')
count++;
由于现在“12345”不会被视为单词。
同样count
对空格进行计数,因此字数再增加一个:因此3而不是5。
你的sentence
似乎有意计算终止NUL。
如果你想计算包含字母的真实单词,请使用bool状态,以确定字母中当前和先前的状态是否不同。
如上所述,您的代码可以溢出。