用c语言编写编写程序进行公民身份证信息验证,运行程序输入身份证号码,对所输入的身份证号码进行验证,验证身份证号码的校验位是否正确。如果正确,则输出该身份证的出生年月日。
时间: 2024-03-18 13:42:45 浏览: 23
好的,以下是用C语言实现身份证信息验证的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
// 验证身份证号码的函数
int validate_id_number(const char* id_number, char* birth_date_str) {
// 身份证号码的正则表达式
const char* pattern = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})(\\d|[Xx])$";
regex_t reg;
regmatch_t matches[7];
if (regcomp(®, pattern, REG_EXTENDED) != 0) {
return 0;
}
if (regexec(®, id_number, 7, matches, 0) != 0) {
regfree(®);
return 0;
}
// 获取身份证号码中的各个字段
char city_code[7];
char year[5];
char month[3];
char day[3];
char seq[4];
char check_digit[2];
memset(city_code, 0, sizeof(city_code));
memset(year, 0, sizeof(year));
memset(month, 0, sizeof(month));
memset(day, 0, sizeof(day));
memset(seq, 0, sizeof(seq));
memset(check_digit, 0, sizeof(check_digit));
strncpy(city_code, id_number + matches[1].rm_so, matches[1].rm_eo - matches[1].rm_so);
strncpy(year, id_number + matches[2].rm_so, matches[2].rm_eo - matches[2].rm_so);
strncpy(month, id_number + matches[3].rm_so, matches[3].rm_eo - matches[3].rm_so);
strncpy(day, id_number + matches[4].rm_so, matches[4].rm_eo - matches[4].rm_so);
strncpy(seq, id_number + matches[5].rm_so, matches[5].rm_eo - matches[5].rm_so);
strncpy(check_digit, id_number + matches[6].rm_so, matches[6].rm_eo - matches[6].rm_so);
// 验证校验位
int factors[17] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
int check_sum = 0;
for (int i = 0; i < 17; i++) {
check_sum += (id_number[i] - '0') * factors[i];
}
int remainder = check_sum % 11;
char check_digit_map[] = "10X98765432";
if (toupper(check_digit[0]) != check_digit_map[remainder]) {
regfree(®);
return 0;
}
// 返回出生年月日
sprintf(birth_date_str, "%s-%s-%s", year, month, day);
regfree(®);
return 1;
}
int main() {
char id_number[19];
char birth_date_str[11];
time_t t;
struct tm* tm_info;
// 获取当前时间(用于计算年龄)
time(&t);
tm_info = localtime(&t);
// 输入身份证号码
printf("请输入身份证号码:");
scanf("%s", id_number);
// 验证身份证号码
if (validate_id_number(id_number, birth_date_str)) {
// 计算年龄
int birth_year = atoi(birth_date_str);
int current_year = tm_info->tm_year + 1900;
int age = current_year - birth_year;
if (age < 0 || age > 150) {
printf("身份证号码不正确!\n");
} else {
printf("该身份证的出生年月日为:%s\n", birth_date_str);
}
} else {
printf("身份证号码不正确!\n");
}
return 0;
}
```
在上述程序中,我们使用了POSIX标准的正则表达式库来匹配身份证号码,并获取了身份证号码中的各个字段。然后,我们使用Luhn算法来验证身份证号码的校验位是否正确。最后,如果身份证号码正确,我们就计算出出生年月日,并使用ctime库中的localtime函数获取当前时间,以此计算出年龄。