代码在C中没有按预期工作

时间:2016-04-27 09:25:54

标签: 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;
}

我在Java中使用了相同的逻辑,它运行良好。有人可以解释什么是错的吗?

2 个答案:

答案 0 :(得分:5)

代码中的问题与sentence的定义有关。当你省略数组维度并初始化它时,数组的大小将由初始化程序的长度决定。

引用strcat()

man page
  

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状态,以确定字母中当前和先前的状态是否不同。

如上所述,您的代码可以溢出。