我一直在尝试创建一个程序,从用户那里获取一个数组并检查它是否是彼此相邻的任何重复字符,如果存在,程序会要求用户再次输入数组但由于某种原因我的程序只要求用户输入一次数组.
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)
代码段可以按以下方式查找
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)