首页 > 解决方案 > 如何计算仅以特定单词为后缀且仅作为后缀的单词数量?

问题描述

所以我有这个,我想:

For the word "are":

caramare
aresdn
lasrare
aresare
mare

We have n=3因为只有 3 个单词以我们的特定单词结尾,并且只有一次。如果我读错了单词,比如“ares”,it will break the program.那是为什么呢?需要从以下位置启动程序:

n=.....;
for(i=1;i<=11;i++)
{ cin>>s; | scanf(“%s”,s);
 ............
}

这是我尝试过的:

#include <stdio.h>
#include <string.h>
int main()
{
    char s[20][20];
    int n=0;
    int i;
    for(i=1;i<=11;i++)
    {
        scanf("%s",s);
        if(strcmp ( strstr("are",s[i]) ,"are") ==0 )
        {
            n++;
        }

    }
    printf("%d",n);
}

标签: c

解决方案


一个问题是,strstr如果找不到针头,则返回 NULL。然后你传递一个 NULL 指针,strcmp它会出错。

你需要像这样拆分它:

    char* tmp = strstr("are",s[i]);
    if (tmp)
    {
        if (strcmp ( tmp ,"are") ==0 )
        {
            n++;
        }
    }

和这个

char s[20][20];

应该是:

char s[20];

并且请永远,永远不要做scanf("%s",s);Always - 就像always,allways,allways - 设置一个限制 - 就像scanf("%19s",s);用户不能溢出你的输入缓冲区一样。


推荐阅读