关于C#:std :: strtol和std :: stoi之间有什么区别?

What are the differences between std::strtol and std::stoi?

免责声明:链接至cppreference.com

所以一段时间以来我就知道std :: atoi已被弃用,建议改用std :: strtol。

C 11引入了std :: stoi,我试图理解为什么人们会选择在std::strtol上使用它。

据我了解,stoi调用strtol但抛出异常。而且它返回一个整数而不是long。

这些主要区别是什么,我想念什么?


Are these the main differences, what am I missing?

较新的std::stoi也可以直接在std::string中使用(因此您不必通过.c_str()调用来乱码),并可以选择通过size_t为您提供第一个不匹配的字符作为索引,而不是作为指针。

这些更改简化了代码中的用法。


相对于strtol(),我更喜欢stoi(),因为前者在无效输入上抛出std :: invalid_argument。破坏GNU libstdc中的异常消息没有帮助。例如:" what():stoi"


如果要传递std::basic_string并且想要获取int,则可以使用std::stoi()。如果您想退出long,请致电std::stol()


一个很大的区别是stoistd::string作为其参数,因此您不必将.c_str()附加到字符串上即可将其转换为整数。

如果要转换为long,则可以改用stol(同样,stodstof stoldstoulstoll可以转换为double, floatlong doubleunsigned longlong long)。


std:stoi与C不兼容,并且与<string>库一起打包,该库具有其他面向对象的实现,这些实现不能由C编译器编译。它的主要用例场景(应该)涉及std:string而不是字节数组,以符合现代C的惯例。


实际上,我真的很奇怪为什么没有std :: FromString模板函数将要将字符串转换为的类型作为模板参数。同样,ToString模板函数执行相反的操作。

您可以轻松想象使用插入和提取运算符的实现。

1
2
3
4
int i = std::FromString <int> (std::string ("2"))
int j = std::FromString <int> ("2")

std::string = ToString <double> (3.14159)

是的,当然,函数名没有大写字母,可能是from_string和to_string。

模板专门化是可能的。
最后,确实没有任何限制,类型必须是本机类型,对吗?