问题描述
我有一个 std::string
,它可以是一个字符串,也可以是一个值(例如 0
).
I have a std::string
which could be a string or could be a value (such as 0
).
将 std::string
转换为具有失败能力的 int
的最佳或最简单的方法是什么?我想要 C# 的 Int32.TryParse
的 C++ 版本.
What is the best or easiest way to convert the std::string
to int
with the ability to fail? I want a C++ version of C#'s Int32.TryParse
.
推荐答案
使用 boost::lexical_cast.如果无法完成转换,它将抛出异常.
Use boost::lexical_cast. If the cast cannot be done, it will throw an exception.
<小时>
没有提升:
Without boost:
<小时>
虚假提升:
Faking boost:
<小时>
如果你想要这些函数的无抛出版本,你必须捕获适当的异常(我不认为 boost::lexical_cast
提供无抛出版本),比如这个:
If you want no-throw versions of these functions, you'll have to catch the appropriate exceptions (I don't think boost::lexical_cast
provides a no-throw version), something like this:
这篇关于在 C++ 中使用 bool/fail 将字符串转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!