簡體   English   中英

以特定格式驗證 C++ 用戶輸入

[英]validating c++ user input in specific format

如何以某種特定格式驗證用戶輸入。 例如,

社會安全號碼,格式為xxx-xx-xxxx ,其中 x 是 0 到 9 范圍內的數字。只接受有效的社會安全號碼(無字母字符)

員工編號,格式為xxx-L ,其中 x 是 0 到 9 范圍內的數字,L 是 A 到 M 范圍內的字母。

#include<iostream> 
#include <string>

class Employee
{
protected:
    string name;
    string ssn; // social security number in format xxx-xx-xxxx
    string empNo; // employee number in format xxx-L
    string date;

public:Employee(){
    
}

void printEmp()
{
    cout << "\n Name : " << name;
    cout << "\n Hire Date : " << date;
    cout << "\n Soc Sec # : " << ssn;
    cout << "\n Employee # : " << empNo;
} 

void getName(){
}

void setName(string n){
name = n

}

我在考慮你沒有接受-輸入。 您可以簡單地循環字符串並使用isalphaisdigit等函數。 對於 A 到 M 的特定范圍,您可以直接進行比較。 例如:

string s="ABCXYZ";
bool satisfied = false;
for(int i=0; i<s.size(); ++i){
    if(s[i]<="M" && s[i]>="A"){
        //this satisfies your criteria
        satisfied = true;
    }else {
        satisfied = false;
        break;
    }
}
if(!satisfied){
    cout<<"Invalid input"<<"\n";
}

對於isalphaisdigit函數,你可以用谷歌搜索它們!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM