为什么没有 std::stou?
C++11 添加了一些新的字符串转换函数:
http://en.cppreference。 com/w/cpp/string/basic_string/stoul
包括stoi(string转int)、stol(string转long)、stoll(string转long long)、stoul(string转unsigned long)、stoul (字符串为 unsigned long long)。值得注意的是它没有一个 stou(字符串到无符号)函数。是否有某种原因不需要它,但其他所有都需要?
C++11 added some new string conversion functions:
http://en.cppreference.com/w/cpp/string/basic_string/stoul
It includes stoi (string to int), stol (string to long), stoll (string to long long), stoul (string to unsigned long), stoull (string to unsigned long long). Notable in its absence is a stou (string to unsigned) function. Is there some reason it is not needed but all of the others are?
related: No "sto{short, unsigned short}" functions in C++11?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最恰当的答案是 C 库没有相应的“
strtou
”,而 C++11 字符串函数都只是 C 库函数的薄薄的包装:std: :sto*
函数镜像strto*
,而std::to_string
函数使用sprintf
。编辑:正如 KennyTM 指出的,
stoi
和stol
都使用strtol
作为底层转换函数,但仍然很神秘,为什么存在 <使用strtoul
的code>stoul,没有对应的stou
。The most pat answer would be that the C library has no corresponding “
strtou
”, and the C++11 string functions are all just thinly veiled wrappers around the C library functions: Thestd::sto*
functions mirrorstrto*
, and thestd::to_string
functions usesprintf
.Edit: As KennyTM points out, both
stoi
andstol
usestrtol
as the underlying conversion function, but it is still mysterious why while there existsstoul
that usesstrtoul
, there is no correspondingstou
.我不知道为什么存在
stoi
而不是stou
,但stoul
和假设的stou
之间的唯一区别将检查结果是否在unsigned
范围内:(同样,
stoi
也类似于stol
,只是范围不同检查;但由于它已经存在,所以没有必要担心具体如何实施。)I've no idea why
stoi
exists but notstou
, but the only difference betweenstoul
and a hypotheticalstou
would be a check that the result is in the range ofunsigned
:(Likewise,
stoi
is also similar tostol
, just with a different range check; but since it already exists, there's no need to worry about exactly how to implement it.)使用掩码以掩码中表示的预期值大小(以位为单位)来执行此操作,不仅适用于 64 位长整型与 32 位整型,也适用于 32 位长整型与 32 位整型。
在 64 位长整型的情况下,~0xffffffffl 将变为 0xffffffff00000000,从而查看是否设置了任何前 32 位。对于 32 位长整型,~0xffffffffl 变为 0x00000000,并且掩码检查将始终为零。
Using masks to do this with the expected value size in bits expressed in the mask, will make this work for 64-bit longs vs 32-bit ints, but also for 32-bit longs vs 32-bit ints.
In the case of 64-bit longs, ~0xffffffffl will become 0xffffffff00000000 and will thus see if any of the top 32 bits are set. With 32-bit longs, it ~0xffffffffl becomes 0x00000000 and the mask check will always be zero.