我尝试为std::snprintf
创建最小缓冲区,将uint64_t
转换为std::string
,并在转换后的字符串中找到大值的错误
#include <cstdio>
#include <inttypes.h>
#include <limits>
#include <string>
#include <cstdint>
// assume this is maximum string size to represent any unsigned integer
// with 1 extra byte for string terminating null character
const std::size_t MAX_UINT64_WIDTH =
std::numeric_limits<std::uint64_t>::digits10 + 1;
int main(int, char**)
{
uint64_t value = 10244450920698242790ULL;
const std::string svalue = "10244450920698242790";
std::string str;
char buf[MAX_UINT64_WIDTH];
auto l = std::snprintf(buf, MAX_UINT64_WIDTH, "%" PRIu64, value);
if (l > 0) {
str.assign(buf, buf + l);
}
assert(svalue == str); //assertion failed, the last character '0' (0x30) is replaced with '\0' (0x00)
return 0;
}
然后我发现assert(21 == MAX_UINT64_WIDTH);
也失败了。最后,最小程序显示错误
#include <limits>
#include <iostream>
#include <string>
#include <cstdint>
int main(int, char**) {
std::cout << std::numeric_limits<std::uint64_t>::max() << std::endl;
std::cout << std::numeric_limits<std::uint64_t>::digits10 << std::endl;
std::cout << std::to_string(std::numeric_limits<std::uint64_t>::max()).size() << std::endl;
return 0;
}
user@host:~$ g++ --std=c++11 -o check check.cpp
user@host:~$ ./check
18446744073709551615
19
20
user@host:~$ g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 5.4.0-6ubuntu1~16.04.5' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-5-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-5-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-5-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)
更新
我滥用了库digits10
所以我重命名了我的问题。
答案 0 :(得分:5)
digits10
是一个数字的位数,你可以安全地&#34;存储在那种类型。例如,如果std::numeric_limits<std::uint64_t>::max()
为18446744073709551615
,则您无法在uint64_t
中存储具有相同位数且所有数字等于9的数字。
可以说,如果max
有N
个数字,则digits10
通常为N-1
(除非max
为99999 ... 9999)。< / p>