请给我C语言编程的:帐号:6<=长度必须<=14,组成必须:只能包含字母、数字 密码:6<=长度必须<=18,以字母开头,只能包含字母、数字和下划线 确认密码:与密码字符串相同。的代码
时间: 2023-06-01 22:05:33 浏览: 204
好的,我可以为您提供C语言编程的代码实现。请参考以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_USERNAME_LENGTH 14
#define MIN_USERNAME_LENGTH 6
#define MAX_PASSWORD_LENGTH 18
#define MIN_PASSWORD_LENGTH 6
void validate_input(char input[], int min_length, int max_length, int allow_space)
{
int length = strlen(input);
if (length < min_length || length > max_length)
{
printf("Invalid input! Input length should be between %d and %d.\n", min_length, max_length);
exit(0);
}
if (!allow_space)
{
for (int i=0; i<length; i++)
{
if (isspace(input[i]))
{
printf("Invalid input! Input should not contain spaces.\n");
exit(0);
}
}
}
}
void validate_username(char username[])
{
validate_input(username, MIN_USERNAME_LENGTH, MAX_USERNAME_LENGTH, 0);
for (int i=0; i<strlen(username); i++)
{
if (!isalnum(username[i]))
{
printf("Invalid username! Username should only contain letters and digits.\n");
exit(0);
}
}
}
void validate_password(char password[], char confirm[])
{
validate_input(password, MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH, 0);
if (!isalpha(password[0]))
{
printf("Invalid password! Password should start with a letter.\n");
exit(0);
}
for (int i=1; i<strlen(password); i++)
{
if (!isalnum(password[i]) && password[i] != '_')
{
printf("Invalid password! Password should only contain letters, digits and underscore.\n");
exit(0);
}
}
if (strcmp(password, confirm) != 0)
{
printf("Password does not match the confirm password.\n");
exit(0);
}
}
int main()
{
char username[MAX_USERNAME_LENGTH + 1];
char password[MAX_PASSWORD_LENGTH + 1];
char confirm[MAX_PASSWORD_LENGTH + 1];
printf("Please enter your username (length should be between %d and %d, and only contain letters and digits): ", MIN_USERNAME_LENGTH, MAX_USERNAME_LENGTH);
fgets(username, sizeof(username), stdin);
username[strcspn(username, "\n")] = 0; // remove trailing newline
validate_username(username);
printf("Please enter your password (length should be between %d and %d, start with a letter, and only contain letters, digits and underscore): ", MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH);
fgets(password, sizeof(password), stdin);
password[strcspn(password, "\n")] = 0; // remove trailing newline
printf("Please confirm your password: ");
fgets(confirm, sizeof(confirm), stdin);
confirm[strcspn(confirm, "\n")] = 0; // remove trailing newline
validate_password(password, confirm);
printf("Your username is: %s\n", username);
printf("Your password is: %s\n", password);
return 0;
}
```
这个代码实现了一个用户注册程序,要求输入用户名和密码,然后验证它们是否符合要求。具体来说,要求用户名长度在6到14之间,只包含字母和数字;密码长度在6到18之间,以字母开头,只包含字母、数字和下划线。代码会检查输入是否符合要求,并且在输入无效时打印错误消息并退出程序。如果输入有效,则输出用户名和密码。
阅读全文