验证字符串仅是数字并且只有一定的长度

时间:2018-11-08 21:42:32

标签: c++ string int

所以我有一个问题。

我需要一个字符串(我不能将其作为整数,必须将其定义为字符串),并且在set方法内部,我必须验证数字长度为9或13位数字并且包含仅数字。

我可以使用str.length()来验证长度,但是我无法通过它来验证输入中仅包含数字。

这是我当前的代码:

void Book::setISBN(string ISBN) 
{

//validate the length here  ALSO NEED TO VALIDATE ITS A NUMBER

if (ISBN.length() >= 9 && ISBN.length() <= 13) {

    this->ISBN = ISBN;
}
else {
    this->ISBN = '0';
}
}

这是将提取信息的代码:

Book b = Book();
b.setISBN("23");
b.setAuthor("R.L. Stine");
b.setTitle("Goosebumps");
b.setPrice(25.00);

Book b2 = Book("thisisshith", "Stephen King", "IT", 20.32);

第一部分b作为setISBN(“ 23”)将以零返回,而b2“ thisisshith”则返回。我也需要它返回0。如果它是一组长度在9到13之间的数字,那么它将正确返回。

任何帮助将不胜感激。

我尝试过isdigit(),但是说它不能在字符串和整数之间转换。

2 个答案:

答案 0 :(得分:2)

在您的SqlCommand sqlCommand = new SqlCommand(@" SELECT Value FROM ConfigurationValue cv INNER JOIN ConfigurationFilter cf ON cv.idConfigurationValue = cf.idConfigurationValue INNER JOIN ConfigurationKey ck ON ck.idConfigurationKey = cf.idConfigurationKey WHERE ck.KeyName = @ConfigurationKey AND((cf.idDomain = @idDomain) OR(cf.idDomain IS NULL)) AND((cf.idBusinessUnit = @idBusinessUnit) OR(cf.idBusinessUnit IS NULL))", dbConnection); sqlCommand .CommandTimeout = 500; 构造函数中,确保它正在调用Book而不是直接设置setISBN()

this->ISBN

然后,在Book::Book(string ISBN, ...) { //this->ISBN = ISBN; this->setISBN(ISBN); ... } 内,您可以执行以下操作:

setISBN()

如果您想改用void Book::setISBN(string ISBN) { if (((ISBN.length() == 9) || (ISBN.length() == 13)) && (ISBN.find_first_not_of("0123456789") == string::npos)) { this->ISBN = ISBN; } else { this->ISBN = '0'; } } ,则需要一个循环来检查字符串中的每个isdigit()。您可以手动执行以下操作:

char

或者,您可以使用标准搜索算法,例如#include <cctype> void Book::setISBN(string ISBN) { if ((ISBN.length() == 9) || (ISBN.length() == 13)) { for (int i = 0; i < ISBN.length(); ++i) { if (!isdigit(static_cast<unsigned char>(ISBN[i]))) { this->ISBN = '0'; return; } } this->ISBN = ISBN; } else { this->ISBN = '0'; } } std::find()

std::all_of()

#include <algorithm>
#include <cctype>

void Book::setISBN(string ISBN) 
{
    if (((ISBN.length() == 9) || (ISBN.length() == 13)) &&
        (std::find(ISBN.begin(), ISBN.end(), [](char ch){ return !isdigit(static_cast<unsigned char>(ch)); }) == ISBN.end()))
    {
        this->ISBN = ISBN;
    }
    else
    {
        this->ISBN = '0';
    }
}

答案 1 :(得分:1)

想通了!

代码中还有一部分是

Book::Book(string ISBN, string author, string title, double price) {
this->ISBN = ISBN;
this->author = author;
this->title = title;
this->price = price;`

我将此添加到该行的末尾:

    if ((ISBN.length() == 9) || (ISBN.length() == 13) &&
    ISBN.find_first_not_of("0123456789") == string::npos)
{
    this->ISBN = ISBN;
}
else {
    this->ISBN = '0';
}

这解决了我需要解决的问题。谢谢!