我正在用 C 编写一个程序来计算句子中的空格数。但我没能让它正常工作。如果我输入类似 Hello world 1234 how are you 的内容,当预期输出为 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 中使用了相同的逻辑,并且运行良好。谁能解释一下出了什么问题?
最佳答案
您的代码中的问题在于 sentence
的定义。当您省略数组维度并对其进行初始化时,数组的大小将由初始化程序的长度决定。
引用man page strcat()
The
strcat()
function appends thesrc
string to thedest
string, overwriting the terminating null byte ('\0') at the end ofdest
, and then adds a terminating null byte. The strings may not overlap, and thedest
string must have enough space for the result. Ifdest
is not large enough, program behavior is unpredictable;
也就是说,程序将调用undefined behavior .
这样,sentence
的内存肯定比它应该容纳的要少得多。此外,strcat()
根本不是必需的。
正确的做法是
- 用适当的维度定义
sentence
,比如char sentence[MAXSIZE] = {0};
,其中MAXSIZE
将是一个宏您选择的尺寸。 - 使用
fgets()
读取用户输入。 - 使用
isspace()
(来自ctype.h
)在一个循环中检查输入字符串中是否存在空格。
关于代码在 C 中未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36885634/