2016-04-20 24 views
1

我正在項目中提示用戶輸入郵政編碼。我需要驗證它是一個五位數字(我不需要驗證它是一個實際的郵政編碼)。驗證用戶輸入是5位數字

這是我的代碼的一部分。

string userInput; 
cout << "Zip Code> "; 
getline(cin, userInput, '\n'); 


while (stoi(userInput)<10000 || stoi(userInput) > 99999){ 
    cout << endl << endl << "You must enter a valid zip code. Please try again." << endl; 
    cout << "Zip Code>" << endl; 
    getline(cin, userInput, '\n'); 
} 

PropertyRec.setZipCode(stoi(userInput)); 

這工作正常,除非郵政編碼以零開頭。如果是這樣,驗證不好,一旦輸入字符串轉換爲整數,初始零不會保存到變量中。

保存到數據庫時,我應該將郵政編碼保留爲字符串嗎?如果是這樣,我如何確認有5個字符,每個字符都是數字?

+1

把它作爲一個字符串,並檢查其大小()? –

+0

只需檢查輸入中是否有五個字符,並且每個字符都是數字。 –

+0

另外,除非你需要額外的東西,否則不要使用'std :: endl'。 ''\ n''結束一行。 –

回答

8

使用std::all_ofisdigitstring::size()以確定郵政編碼是有效的:

#include <string> 
#include <algorithm> 
#include <cctype> 
//... 
bool isValidZipCode(const std::string& s) 
{ 
    return s.size() == 5 && std::all_of(s.begin(), s.end(), ::isdigit); 
} 

Live Example

Declarative Programming插頭:

注意,如果你大聲說出在該行isValidZipCode函數,它適合你的描述(字符串必須有一個大小等於5,「all of」charact ers必須是數字)。

+0

謝謝你們!很棒。 – Brent

4

既然你接收輸入爲std::string,你可以使用std::string::length(或std::string::size),以確保您有字符適量:

if (userInput.length() != 5) 
{ 
    // Input is invalid 
} 

,以確保它們是唯一號碼,如@ user4581301點出可以使用std::all_ofisdigit(或this question檢查出答案)

if (userInput.length() == 5 && std::all_of(s.begin(), s.end(), ::isdigit)) 
{ 
    // Input is valid 
} 

另外值得一提的是以下行

PropertyRec.setZipCode(stoi(userInput)); 

將消除任何導致0你有,那麼你可能需要存儲您的郵政編碼爲std::string(除非你執行的處理,將承擔任何郵政編碼這< 5已經0領先的,但它可能更容易以完全按原樣存儲)

0

您可以使用字符串大小函數獲取字符串的大小。將字符串大小保存在其他變量中,並驗證它是否小於5。