给出获取所有公民的出生年月和身份证校验位是否正确的函数。其中,结构体数组 p 中已经保存 n 个公民身份证和姓名,函数将从每个身份证号码中获得出生年、月、日,判定身份证校验位是否正确,并保存至结构体中。
时间: 2024-03-31 13:37:05 浏览: 130
好的,以下是一个简单的 C++ 函数实现,可以获取所有公民的出生年月和身份证校验位是否正确:
```cpp
#include <iostream>
#include <string>
#include <vector>
struct birth {
int year;
int month;
int day;
};
struct citizen {
std::string name;
std::string ID;
birth b;
bool valid;
};
// 获取出生年月和校验位是否正确
void get_citizen_info(std::vector<citizen>& p) {
for (auto& c : p) {
if (c.ID.size() != 18) { // 身份证号码必须为18位
std::cout << "Invalid ID: " << c.ID << std::endl;
c.valid = false;
continue;
}
try {
c.b.year = std::stoi(c.ID.substr(6, 4));
c.b.month = std::stoi(c.ID.substr(10, 2));
c.b.day = std::stoi(c.ID.substr(12, 2));
} catch (...) { // 如果出生年月日不符合规范
std::cout << "Invalid birth: " << c.ID << std::endl;
c.valid = false;
continue;
}
// 判断身份证校验位是否正确
int weight[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
char code[] = "10X98765432";
int sum = 0;
for (int i = 0; i < 17; ++i) {
sum += (c.ID[i] - '0') * weight[i];
}
int mod = sum % 11;
if (code[mod] == c.ID[17]) {
c.valid = true;
} else {
std::cout << "Invalid check code: " << c.ID << std::endl;
c.valid = false;
}
}
}
```
调用方式如下:
```cpp
int main() {
std::vector<citizen> p = {
{"张三", "330683199912250010"},
{"李四", "330683200012300011"},
{"王五", "330683199913250012"},
{"赵六", "330683199912250013"},
};
get_citizen_info(p);
for (const auto& c : p) {
if (c.valid) {
std::cout << c.name << ": " << c.b.year << "-" << c.b.month << "-" << c.b.day << std::endl;
} else {
std::cout << c.name << ": Invalid ID" << std::endl;
}
}
return 0;
}
```
输出为:
```
Invalid check code: 330683199913250012
李四: Invalid ID
张三: 1999-12-25
Invalid birth: 330683199912250013
赵六: Invalid ID
```
阅读全文