【发布时间】: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