验证用户输入是5位数

Bre*_*ent 1 c++

我正在开发一个项目,提示用户输入邮政编码.我需要验证它是一个五位数字(我不需要验证它是一个真正的邮政编码).

这是我的一部分代码.

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));
Run Code Online (Sandbox Code Playgroud)

除非邮政编码以零开头,否则此工作正常.如果是,则验证不好,并且一旦输入字符串转换为整数,初始零就不会保存到变量.

保存到数据库时,我应该将邮政编码保留为字符串吗?如果是这样,我如何验证正好有5个字符,每个字符都是数字?

Pau*_*zie 8

使用std :: all_of,isdigitstring::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);
}
Run Code Online (Sandbox Code Playgroud)

实例

声明性编程插件:

请注意,如果您大声说出isValidZipCode函数中的行,它符合您的描述(字符串的大小必须等于5,"所有"字符必须是数字).