c++中类与对象相关

程序中要求用户输入正确的18位身份证号码,程序输出该号码。18位身份证号码中前17位由09的数字组成、第18为校验码(可以是09或X)。如何确保这一点?设计程序确保用户输入了这样的字符串且没有多输。程序运行情况为:

Please enter your ID number:430512200208131367678

Incorrect ID number,reenter:43051220020813136x

Incorrect ID number,reenter:43051220020813ab6X

Incorrect ID number,reenter:430512 20030813 136 7

430512200308131367

说明:冒号前为程序提示,最后一行为程序输出用户输入正确的身份证号码。

可以使用C++中的正则表达式库regex来验证身份证号码是否合法,代码如下:

#include<iostream>
#include<regex>
using namespace std;

int main()
{
    regex pattern("\\d{17}[0-9Xx]"); // 正则表达式,匹配17位数字和最后一位数字或X或x
    string id;
    cout << "Please enter your ID number:";
    cin >> id;
    while(!regex_match(id, pattern)) // 如果输入不合法,则循环提示用户重新输入
    {
        cout << "Incorrect ID number,reenter:";
        cin >> id;
    }
    cout << id << endl;
    return 0;
}