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

Ofe*_*zon 1 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++;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 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 );
Run Code Online (Sandbox Code Playgroud)

或者它可以写成

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 );
Run Code Online (Sandbox Code Playgroud)

  • 弗拉德,同时检查字符是否相同.不应该是`!=`然后`if(*p)......`? (2认同)
  • Vlad,现在修复`if(!*p)`,它检查循环到达结尾(没有重复)到`if(*p)`,它检查在结束之前退出的循环(看到重复). (2认同)