代码无法按预期在C中工作 [英] Code not working as expected in C

查看:78
本文介绍了代码无法按预期在C中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C语言开发一个程序,计算一个句子中的空格数。但是我没有设法使其正常运行。如果我输入类似 Hello world 1234的样子,那么当预期输出为5时,我得到的输出为3。

我的代码是:

I was working on a program in C to count the number of spaces in a sentence. But I haven't managed to get it to work properly. If I enter something like Hello world 1234 how are you the output I'm getting is 3 when the output expected is 5.
My code is :

//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中使用了相同的逻辑,并且运行良好。

I used the same logic in Java and it worked fine. Could someone explain whats going wrong?

推荐答案

您的代码中的问题在于句子的定义。当您忽略数组维度并对其进行初始化时,数组的大小将由初始化程序的长度确定。

The problem in your code is with the definition of sentence. When you leave out the array dimension and initialize it, the size of the array will be determined by the length of the initializer.

引用手册页 of strcat()


strcat()函数附加 src 字符串到 dest 字符串,在 dest 的末尾覆盖终止空字节('\0'),并然后添加一个终止的空字节。字符串可能不会重叠,,并且 dest 字符串必须有足够的空间来存储结果。如果目的地不够大,则程序行为是不可预测的;

The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable;

也就是说,程序将调用未定义的行为

That is, the program will invoke undefined behavior.

这样,句子的内存肯定比它应该保存的要少。此外,根本不需要 strcat()

This way, sentence has certainly way less memory than it it supposed to hold. Moreover, strcat() is not at all required there.

正确的方法


  • 定义句子并带有适当的尺寸,例如 char句子[MAXSIZE] = {0}; ,其中 MAXSIZE 将是一个具有您选择的大小的MACRO。

  • 使用 fgets()读取用户输入。

  • 使用 isspace() (来自 ctype .h )循环检查输入字符串中是否存在空格。

  • Define sentence with a proper dimention, like char sentence[MAXSIZE] = {0};, where MAXSIZE will be a MACRO having the size of your choice.
  • use fgets() to read the user input.
  • use isspace() (from ctype.h) in a loop to check for presence of space in the input string.

这篇关于代码无法按预期在C中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆