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

时间:2016-01-23 10:15:16

标签: c arrays

我一直在尝试创建一个程序,从用户那里获取一个数组并检查它是否是彼此相邻的任何重复字符,如果存在,程序会要求用户再次输入数组但是对于某些原因我的程序只要求用户输入一次数组。

    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++;
        }
    }

3 个答案:

答案 0 :(得分:5)

代码段可以按以下方式显示

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 :(得分:0)

另一种方法是:

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的{​​{1}}会导致您跳过字符。您不需要它,因为i++语句负责增量。

答案 2 :(得分:0)

您在数组之前向strlenpass - 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;
    }
}