循环时无法比较数组中的字符串

时间:2019-01-04 10:28:32

标签: c arrays string

我目前正在我的大学本学期进行期末考试。我想制作一个程序来比较数组中的单词。如果存在与先前输入的单词相同的单词,则程序将结束。

但是我仍然不知道该怎么做。

我尝试更改j,i,并调整strcmp函数,但仍然没有答案。

#include <stdio.h>
#include <string.h>

int main(void)
{
    int a, i, j, ret;
    char kt[255][255];

    printf("\t\t\t\tPlayers: ");
    scanf("%d", &a);

    for(i=0;i<a;i++)
    {
        printf("\t\t\t\tPlayer %d: ", i+1);
        scanf(" %[^\n]s", kt[i]);

        if(i==0)
        {
            continue;
        }

        for(j=i+1;j<a;j++)
        {
            ret=strcmp(kt[i],kt[j]);
            if(ret==0)
            {
                printf("\t\t\t\tPlayer %d, You lose!\n", j+1);
                break;
            }
        }
    }
    printf("\t\t\t\tEnd Game\n");
}

我希望输出会像

Players: 4
Player 1: Test
Player 2: Test1
Player 3: Test
End Game

但是我得到的是

Players: 4
Player 1: Test
Player 2: Test1
Player 3: Test
Player 4: Test
End Game

2 个答案:

答案 0 :(得分:2)

您正在循环错误,使其成功 for(j=0;j<i;j++)而不是for(j=i+1;j<a;j++)

您还必须打破外循环

#include <stdio.h>
#include <string.h>

int main(void)
{
    int a, i, j, ret,flag=0;
    char kt[255][255];

    printf("\t\t\t\tPlayers: ");
    scanf("%d", &a);

    for(i=0;i<a;i++)
    {
        printf("\t\t\t\tPlayer %d: ", i+1);
        scanf(" %[^\n]s", kt[i]);

        if(i==0)
        {
            continue;
        }

    // from j=0 to j< i to compare all previous entries
        for(j=0;j<i;j++)
        {
            ret=strcmp(kt[i],kt[j]);
            if(ret==0)
            {
                printf("\t\t\t\tPlayer %d, You lose!\n", i+1);
                flag=1;  // using break will only break this loop so use flag to break next loop also
                break;
            }
        }
    if (flag==1){
        break;
    }
    }
    printf("\t\t\t\tEnd Game\n");
}

答案 1 :(得分:0)

您应该检查从第一个elem = 0到当前-i:

#include <stdio.h>
#include <string.h>

int main(void)
{
    int a, i, j, ret;
    char kt[255][255];

    printf("\t\t\t\tPlayers: ");
    scanf("%d", &a);

    for(i=0;i<a;i++)
    {
        printf("\t\t\t\tPlayer %d: ", i+1);
        scanf(" %[^\n]s", kt[i]);

        if(i==0)
        {
            continue;
        }

        for(j=0;j<i;j++)
        {
            ret=strcmp(kt[i],kt[j]);
            if(ret==0)
            {
                printf("\t\t\t\tPlayer %d, You lose!\n", i+1);
                goto exit;
            }
        }
    }

    exit:
    printf("\t\t\t\tEnd Game\n");
}