繁体   English   中英

计算C中的句子数

[英]Counting number of sentences in C

这个简单的代码计算通过检查期间,问号或感叹号输入的句子数。 但是,如果我输入“”,它就不会计算空格后的句子。 我怎样才能解决这个问题?

int numberSentence(char ch[])
{
    int count=0, i=0;
    while(ch[i] != '\0')
    {
        if(ch[i] == '.' || ch[i] == '?' || ch[i] == '!')
            count++;
        i++;
    }

    return count;
}


int main()
{
    char ch[999];
    printf("Enter sentences:\n");
    scanf("%s", ch);
    printf("Number of sentences is %d", numberSentence(ch));

}

你的问题在于:

scanf("%s", ch)

带有“%s”的scanf将一直看到它找到一个空白区域,然后将该字符串存储到指针ch中。

在这种情况下,我建议使用:

scanf("%c", ch)

它将逐个字符地扫描。 您需要稍微改造程序。

请注意,scanf()将返回一个整数,表示它读取的宽度。 从而:

while(scanf("%c", ch) == 1)
   if (ch == ...)
}

供您参考: http//www.tutorialspoint.com/c_standard_library/c_function_scanf.htm

如果是空白表示新行密钥,请尝试:

if(ch[i] == '.' || ch[i] == '?' || ch[i] == '!' || ch[i] == '\n')
        count++;

但为什么不直接使用gets()?

while(gets(ch)!=NULL)
{
    count++;
}

对于这个简单的问题,您可以让scanf()使用scanset转换说明符在句子分隔符上拆分输入。

#include <stdio.h>

int main(void) {
    int count = 0;
    char buf[1000];
    while (scanf("%999[^.!?]%*c", buf) == 1) ++count;
    printf("sentences: %d\n", count);
    return 0;
}

%[^.!?]将扫描所有数据,包括句点,感叹号或问号。 %*c将扫描标点符号而不存储它( *表示没有存储扫描输入的参数)。

#include <stdio.h>

int numberSentence(char ch[]){
    int count=0, i;
    char last = ' ';

    for(i = 0; ch[i]; ++i){
        if(ch[i] == '.' || ch[i] == '?' || ch[i] == '!'){
            count++;
            last = ' ';
        } else if(ch[i] == ' ' || ch[i] == '\t' || ch[i] == '\n'){
            continue;//white-space does't include to sentence of top.
        } else {
            last = ch[i];//check for Not terminated with ".?!"
        }
    }

    return count + (last != ' ');//+ (last != ' ') : +1 if Not terminated with ".?!"
}


int main(void){
    char ch[1000];

    printf("Enter sentences:\n");
    scanf("%999[^\n]", ch);//input upto newline
    printf("Number of sentences is %d", numberSentence(ch));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM