C++ 11引入方便的功能stoi,stol,stoll,stoul,stoull,stof,stod,和stold,其中一个字符串转换为整数,很久长,无符号长,无符号长长整型,浮点,双,或双长分别.
为什么不爱短暂和无条件的短片?
除了遗漏让我原谅我的事实外,我发现自己不得不在这样的情况下笨拙地工作:
#include <string>
struct S
{
    S(short);
};
int main()
{
    S s{std::stoi("4")};
}
错误:
test.cpp: In function 'int main()':
test.cpp:10:23: error: narrowing conversion from 'int' to 'short int' inside { } [-fpermissive]
我想反而写S s{std::stos("4")};,如果只有stos...
相反,我必须写S s{static_cast<short>(std::stoi("4"))};...哦等等,也不会这样做,它会默默地截断整数而不是短路,而不是一个假设的stos函数,如果整数不适合短路则抛出异常.所以基本上我回到我的预C++ 11层的替代品stringstreams,boost::lexical_cast等等.
编辑:既然人们似乎也很难定位我的实际问题,这是为什么没有stos和stous功能,以及其他的人去?
从c ++ 11开始,<string>标头提供:
从转换为std::string有符号整数。
我们也有他们的未签名副本:
现在,即使是一个孩子,也会注意到某些东西丢失了吗?:)
因此问题是:是否有理由不提供std::stoui或仅仅是被遗忘的东西(基本上,这种“显而易见的”东西怎么会被遗忘)?
此外,是否意味着将一个正确的方式std::string来unsigned int为:
unsigned int ui = static_cast<unsigned int>(std::stoul(std::string{"42"}));
免责声明:链接指向cppreference.com
所以我早就知道std :: atoi已被弃用,并且建议使用std :: strtol.
C++ 11引入了std :: stoi,我试图理解为什么会选择使用它std::strtol.
根据我的理解,stoi调用strtol但抛出异常.它还返回一个整数而不是long.
这些是主要的差异,我错过了什么?