检查数组中重复字符的程序

问题描述 投票:0回答:3

我一直在尝试制作一个程序,从用户那里获取一个数组,并检查其中是否有任何相邻的重复字符,如果有,程序会要求用户再次输入数组,但由于某种原因我的程序只要求用户输入数组一次。

    printf("Please enter your private password: ");
    fgets(pass, MAX_LEN, stdin);

    for (i = 0; i < strlen(pass - 1); i++) {
        if (pass[i] == pass[i + 1]) {
            printf("You entered duplicated numbers! \n");
            printf("Please enter your private password: ");
            fgets(pass, MAX_LEN, stdin);
        } else {
            i++;
        }
    }
arrays c duplicates c-strings
3个回答
6
投票

代码片段可以如下所示

char *p = NULL;
do
{
    printf( "Please enter your private password: " );
    if ( ( p = fgets( pass, MAX_LEN, stdin ) ) != NULL )
    {
        while ( *p && *p != *( p + 1 ) ) ++p;  

        if ( *p != '\0' )
        {
            printf("You entered duplicated numbers! \n");
            p = NULL;
        }
    }
} while ( p == NULL );

或者也可以这样写

int valid = 0;

do
{
    char *p = pass;

    printf( "Please enter your private password: " );

    if ( !fgets( pass, MAX_LEN, stdin ) ) break;

    while ( *p && *p != *( p + 1 ) ) ++p;  

    valid = *p == '\0';
    if ( !valid  )
    {
        printf("You entered duplicated numbers! \n");
    }
} while ( !valid );

1
投票

您向

strlen
传递了一个无效的指针:
pass - 1
指向数组之前。 您应该使用
strlen(pass) - 1

要重新提示用户输入数组,您应该有一个单独的循环来读取密码并检查重复字符:

这是更正后的版本:

for (;;) {
    printf("Please enter your private password: ");
    if (!fgets(pass, MAX_LEN, stdin)) {
        /* end if file reached */
        return -1;
    }
    size_t i;
    for (i = 0; pass[i] != '\0'; i++) {
        if (pass[i] == pass[i + 1])
            break;
        }
    }
    if (pass[i]) {
        printf("You entered duplicated numbers! \n");
    } else {
        break;
    }
}

1
投票

另一种方法是:

char    * GetStrPtr;        //  pointer return value for get string
bool    InvPwd = true;      //  flag for invalid password; true to force execution of while

printf("Please enter your private password: ");
GetStrPtr = fgets(pass, MAX_LEN, stdin);
while (GetStrPtr != NULL && pass[0] != '\0'  && InvPwd == true) {

    InvPwd = false;
    for (i = 0; i < strlen(pass) - 1; i++)
        if (pass[i] == pass[i + 1]) {
            printf("You entered duplicated numbers! \n");
            printf("Please enter your private password: ");
            GetStrPtr = fgets(pass, MAX_LEN, stdin);
            InvPwd = true;
            break;
        }
}

正如其他人指出的那样,问题在于

strlen(pass - 1);
。 另外,我相信
else
i++
会导致您跳过字符。 您不需要它,因为
for
语句负责增量。

© www.soinside.com 2019 - 2024. All rights reserved.