【问题标题】:Short circuit evaluation VS 2017 c++短路评估VS 2017 c++
【发布时间】:2017-09-10 21:52:37
【问题描述】:

我正在尝试使用 std::string 从用户那里获取一个数字,并想先检查该字符串是否为空且仅包含数字,然后检查该数字是否大于零

当我构建它并按下回车键时,我在 stoi 函数中得到一个未处理的无效参数异常。

我在旧版本的 VS (2012) 中尝试它,并得到相同的错误。

短路评估是否适用于 VS?

static const bool is_number(const char caracter)
{
    return(caracter >= '0' && caracter <= '9');
}

template <typename T> static const bool all_numbers(const T &str)
{
    if (!str.empty())
    {
        auto it = str.cbegin();

        if ((str.front() == '+' || str.front() == '-') && (str.size()>1)) ++it;

        for (it; it != str.cend(); ++it) if (!is_number(*it))  return false;

        return true;
    }
    else return false;
}

int main()
{
    std::string str;

    do
    {
        std::cout << " Number: ";
        getline(std::cin, str);
        std::cin.clear();

    }while (!all_numbers(str) && std::stoi(str) <= 0);

    return 0;
}

【问题讨论】:

  • 到目前为止,您采取了哪些措施来解决您的问题?
  • 当你遇到这个结果时,你向你的程序提供了什么输入?
  • 当然短路在 VS 上“有效”。这是语言的要求。您应该在调试过程中排除这种解释。
  • 如果all_numbers 返回false,您的逻辑将调用stoi。显然这不是你的意思。
  • 多年来,主要的编译器(尤其是 VS)已经得到了数十万用户的验证。这样的严重错误几乎是不可能的。

标签: c++ visual-studio short-circuiting


【解决方案1】:

当然,短路在 Visual Studio 中有效,您可以自己轻松验证这一点。

但是,你的逻辑是错误的:

(!all_numbers(str) && std::stoi(str) <= 0);

如果输入不是全是数字,你只在执行stoi。那显然是倒退了。

我想也许你打算写 || 代替?

【讨论】:

    猜你喜欢
    • 2012-02-10
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2017-01-21
    • 2010-12-21
    • 1970-01-01
    相关资源
    最近更新 更多