0

所以我有一个问题。

我需要一个字符串(我不能将它作为一个 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() 但说它不能在字符串和 int 之间转换。

4

2 回答 2

2

在您的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()or 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';
    }
}

#include <algorithm>
#include <cctype>

void Book::setISBN(string ISBN) 
{
    if (((ISBN.length() == 9) || (ISBN.length() == 13)) &&
        std::all_of(ISBN.begin(), ISBN.end(), [](char ch)->bool { return isdigit(static_cast<unsigned char>(ch)); }))
    {
        this->ISBN = ISBN;
    }
    else
    {
        this->ISBN = '0';
    }
}
于 2018-11-08T21:47:04.030 回答
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';
}

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

于 2018-11-08T21:57:12.407 回答