1
Diff FBullAndCow::EDifficulty(std::string diff) const
{
    if ((diff.length() > 1))
    {
        return Diff::Not_Number;
    }
    else if (!strchr(diff.c_str(), '3' || '4' || '5' || '6' || '7' || '8'))
    {
        return Diff::Not_Number;
    }
    return Diff::Ok;
}

是否可以使用strchr在字符串中找到多个字符?我尝试了上面的方法,但它不起作用。我想这是因为strchr返回一个字符的出现?

PS:。我试过了

    if ((!strchr(diff.c_str(), '3')) || (!strchr(diff.c_str(), '4')))

也以这种方式使用它,尽管它可能很愚蠢。我是个菜鸟……我确实尝试了几个小时寻找方法,但由于我找不到任何东西,所以我就在这里。

编辑:它需要返回它找到的数字。很抱歉漏掉了这个。

4

1 回答 1

2

直接的答案是:不,您不能在strchr. 该函数只是寻找一个特定的字符。

如果您需要搜索所有数字字符,因为您使用的是 a std::string(为什么要给它起别名?),您可以使用find_first_of(). 或者,更有可能的是find_first_not_of(),检查diff.find_first_not_of("0123456789") == std::string::npos

但是,即使这也不是一个好的解决方案 - 因为大概一旦您验证它是数字,您就会想要实际的数字。std::stoi()因此,仅使用并验证它没有抛出并消耗整个字符串可能更直接。

于 2017-09-21T15:45:02.317 回答