You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言count_sentences函数条件判断报错,求非else if修复方案

问题:修复count_sentences函数的逻辑判断错误

尝试编写if语句检查文本中是否包含.、!或?时持续报错,出错的是count_sentences函数,原代码如下:

int count_letters(string text);
int count_words(string text);
int count_sentences(string text);

int main(void)
{
    string text = get_string("Text: ");
    printf("%s\n", text);

    int letters = count_letters(text);
    printf("%i letters\n", letters);

    int words = count_words(text);
    printf("%i words\n", words);

    int sentences = count_sentences(text);
    printf("%i sentences\n", sentences);
}

int count_letters(string text)
{
    int letters = 0;

    for (int i = 0, len = strlen(text); i < len; i++)
    {
        if (isalpha(text[i]))
        {
            letters++;
        }
    }
    return letters;
}

int count_words(string text)
{
    int words = 0;

    for (int i = 0, len = strlen(text); i < len; i++)
    {
        if (text[i] == ' ')
        {
            words++;
        }
    }
    return words + 1;
}

int count_sentences(string text)
{
    int sentences = 0;

    for (int i = 0, len = strlen(text); i < len; i++)
    {
        if (text[i] == '.' || '!' || '?')
        {
            sentences++;
        }
    }
    return sentences;
}

编译报错信息:

readability.c:66:28: error: use of logical '||' with constant operand [-Werror,-Wconstant- 
logical-operand]
        if (text[i] == '.' || '!' || '?')
                           ^  ~~~
readability.c:66:28: note: use '|' for a bitwise operation
        if (text[i] == '.' || '!' || '?')
                           ^~
                           |
fatal error: too many errors emitted, stopping now [-ferror-limit=]

已知可用else if实现,但希望用当前的逻辑或写法修复,该如何解决?


解决方案

报错原因是逻辑或运算符||的使用错误:C语言中,||两侧必须是完整的布尔表达式,你当前的写法text[i] == '.' || '!' || '?'中,'!'和'?'是字符常量,会被当作非零值(恒为真),这不符合语法要求。

需要给每个符号都补充完整的判断条件,修正后的count_sentences函数如下:

int count_sentences(string text)
{
    int sentences = 0;

    for (int i = 0, len = strlen(text); i < len; i++)
    {
        if (text[i] == '.' || text[i] == '!' || text[i] == '?')
        {
            sentences++;
        }
    }
    return sentences;
}

这样每个条件都明确判断text[i]是否等于对应的标点符号,符合逻辑或的语法规则,编译即可通过。


内容的提问来源于stack exchange,提问作者Boriscodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:15:21