验证用户输入是5位数

时间:2016-04-20 00:12:45

标签: 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));

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

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

3 个答案:

答案 0 :(得分: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,“所有”字符必须是数字)。

答案 1 :(得分: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,但它可能更容易完全按原样存储)

答案 2 :(得分:0)

您可以使用字符串大小函数来获取字符串的大小。将字符串大小保存在其他变量中,并验证它是否小于5。

相关问题