用于将整数转换为字符串 C++ 的 itoa() 替代方案?
我想知道是否有 itoa()
的替代方法来将整数转换为字符串,因为当我在 Visual Studio 中运行它时,我收到警告,当我尝试在 Linux 下构建程序时,我出现编译错误。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我想知道是否有 itoa()
的替代方法来将整数转换为字符串,因为当我在 Visual Studio 中运行它时,我收到警告,当我尝试在 Linux 下构建程序时,我出现编译错误。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(18)
在 C++11 中,您可以使用
std::to_string
:如果您使用的是 C++11 之前的版本,则可以使用 C++ 流:
取自 http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
In C++11 you can use
std::to_string
:If you're working with prior to C++11, you could use C++ streams:
Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
boost::lexical_cast 效果很好。
boost::lexical_cast works pretty well.
考古
itoa 是一个非标准辅助函数,旨在补充 atoi 标准函数,并且可能隐藏了 sprintf (其大部分功能可以用 sprintf 实现): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html
C 方式
使用 sprintf。 或者 snprintf。 或者你找到的任何工具。
尽管事实上有些函数不在标准中,正如“onebyone”在他的评论中正确提到的那样,大多数编译器都会为您提供替代方案(例如,Visual C++ 有它自己的 _snprintf,如果需要,您可以将其 typedef 为 snprintf)。
C++方式。
使用 C++ 流(在当前情况下为 std::stringstream(甚至是已弃用的 std::strstream,如 Herb Sutter 在他的一本书中提出的,因为它速度更快)。
结论
您使用的是 C++,这意味着你可以选择你想要的方式:
更快的方式(即C方式),但你应该确保代码是应用程序中的瓶颈(过早的优化是邪恶的,等等)并且你的代码是安全的封装以避免缓冲区溢出的风险。
更安全的方法(即 C++ 方法),如果您知道这部分代码并不关键,那么最好确保这部分代码不会因为有人误认为大小或指针而在随机时刻中断(这发生在现实生活中,就像......昨天,在我的电脑上,因为有人认为使用更快的方式而不是真正需要它“很酷”)。
Archeology
itoa was a non-standard helper function designed to complement the atoi standard function, and probably hiding a sprintf (Most its features can be implemented in terms of sprintf): http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html
The C Way
Use sprintf. Or snprintf. Or whatever tool you find.
Despite the fact some functions are not in the standard, as rightly mentioned by "onebyone" in one of his comments, most compiler will offer you an alternative (e.g. Visual C++ has its own _snprintf you can typedef to snprintf if you need it).
The C++ way.
Use the C++ streams (in the current case std::stringstream (or even the deprecated std::strstream, as proposed by Herb Sutter in one of his books, because it's somewhat faster).
Conclusion
You're in C++, which means that you can choose the way you want it:
The faster way (i.e. the C way), but you should be sure the code is a bottleneck in your application (premature optimizations are evil, etc.) and that your code is safely encapsulated to avoid risking buffer overruns.
The safer way (i.e., the C++ way), if you know this part of the code is not critical, so better be sure this part of the code won't break at random moments because someone mistook a size or a pointer (which happens in real life, like... yesterday, on my computer, because someone thought it "cool" to use the faster way without really needing it).
尝试 sprintf():
sprintf() 与 printf() 类似,但输出为字符串。
另外,正如 Parappa 在评论中提到的,您可能需要使用 snprintf() 来阻止发生缓冲区溢出(其中您要转换的数字不适合字符串的大小)。它的工作原理如下:
Try sprintf():
sprintf() is like printf() but outputs to a string.
Also, as Parappa mentioned in the comments, you might want to use snprintf() to stop a buffer overflow from occuring (where the number you're converting doesn't fit the size of your string.) It works like this:
在幕后, lexical_cast 会这样做:
如果您不想为此“拖入” boost,那么使用上面的方法是一个很好的解决方案。
Behind the scenes, lexical_cast does this:
If you don't want to "drag in" boost for this, then using the above is a good solution.
我们可以在 C++ 中定义自己的
iota
函数:不要忘记
#include
。We can define our own
iota
function in c++ as:Don't forget to
#include <string>
.С++11 最终解决了这个问题,提供了
std::to_string
。此外,
boost::lexical_cast
对于旧编译器来说是一个方便的工具。С++11 finally resolves this providing
std::to_string
.Also
boost::lexical_cast
is handy tool for older compilers.我使用这些模板
I use these templates
尝试 Boost.Format 或 FastFormat,都是高质量的 C++ 库:
使用 Boost.Format
或 FastFormat
显然,它们所做的不仅仅是单个整数的简单转换
Try Boost.Format or FastFormat, both high-quality C++ libraries:
WIth Boost.Format
or FastFormat
Obviously they both do a lot more than a simple conversion of a single integer
实际上,您可以使用一个巧妙编写的模板函数将任何内容转换为字符串。 此代码示例使用循环在 Win-32 系统中创建子目录。 字符串连接运算符operator+用于连接根与后缀以生成目录名称。 后缀是通过使用模板函数将循环控制变量 i 转换为 C++ 字符串并将其与另一个字符串连接来创建的。
You can actually convert anything to a string with one cleverly written template function. This code example uses a loop to create subdirectories in a Win-32 system. The string concatenation operator, operator+, is used to concatenate a root with a suffix to generate directory names. The suffix is created by converting the loop control variable, i, to a C++ string, using the template function, and concatenating that with another string.
分配足够长度的字符串,然后使用 snprintf。
Allocate a string of sufficient length, then use snprintf.
我不久前编写了这个线程安全函数,对结果非常满意,觉得该算法轻量且精简,性能大约是标准 MSVC _itoa() 函数的 3 倍。
这是链接。 最佳 Base-10 only itoa() 函数? 性能至少是该函数的 10 倍sprintf() 的。 基准测试也是该功能的 QA 测试,如下所示。
关于使用调用者的存储提出了一些愚蠢的建议,这些建议会使结果浮动在调用者地址空间的缓冲区中的某个位置。 别理他们。 正如基准/QA 代码所示,我列出的代码运行良好。
我相信这段代码足够精简,可以在嵌入式环境中使用。 YMMV,当然。
I wrote this thread-safe function some time ago, and am very happy with the results and feel the algorithm is lightweight and lean, with performance that is about 3X the standard MSVC _itoa() function.
Here's the link. Optimal Base-10 only itoa() function? Performance is at least 10X that of sprintf(). The benchmark is also the function's QA test, as follows.
There are some silly suggestions made about using the caller's storage that would leave the result floating somewhere in a buffer in the caller's address space. Ignore them. The code I listed works perfectly, as the benchmark/QA code demonstrates.
I believe this code is lean enough to use in an embedded environment. YMMV, of course.
IMO,最好的答案是这里提供的功能:
http:// www.jb.man.ac.uk/~slowe/cpp/itoa.html
它模仿许多库提供的非 ANSI 函数。
它的速度也快如闪电,并且在 -O3 下优化得很好,而您不使用 c++ string_format() ...或 sprintf 的原因是它们太慢了,对吧?
The best answer, IMO, is the function provided here:
http://www.jb.man.ac.uk/~slowe/cpp/itoa.html
It mimics the non-ANSI function provided by many libs.
It's also lightning fast and optimizes well under -O3, and the reason you're not using c++ string_format() ... or sprintf is that they are too slow, right?
如果您对快速且安全的整数到字符串转换方法感兴趣并且不限于标准库,我可以推荐 format_int 方法/fmtlib/fmt" rel="nofollow noreferrer">{fmt} 库:
根据 来自 Boost Karma 的整数到字符串转换基准,此方法比 glibc 的
sprintf
或std::stringstream 快几倍
。 它甚至比 Boost Karma 自己的int_generator
还要快,独立基准。免责声明:我是这个库的作者。
If you are interested in fast as well as safe integer to string conversion method and not limited to the standard library, I can recommend the
format_int
method from the {fmt} library:According to the integer to string conversion benchmarks from Boost Karma, this method several times faster than glibc's
sprintf
orstd::stringstream
. It is even faster than Boost Karma's ownint_generator
as was confirm by an independent benchmark.Disclaimer: I'm the author of this library.
请注意,所有
stringstream
方法可能涉及锁定使用区域设置对象进行格式化。 如果您从多个线程使用此转换,则可能需要警惕...请参阅此处了解更多信息。 在 C++ 中将数字转换为指定长度的字符串< /a>
Note that all of the
stringstream
methods may involve locking around the use of the locale object for formatting. This may be something to be wary of if you're using this conversion from multiple threads...See here for more. Convert a number to a string with specified length in C++
在 Windows CE 派生平台上,默认情况下没有 iostream。 最好使用
_itoa<>
系列,通常是_itow<>
(因为大多数字符串内容都是 Unicode)。On Windows CE derived platforms, there are no
iostream
s by default. The way to go there is preferaby with the_itoa<>
family, usually_itow<>
(since most string stuff are Unicode there anyway).从技术上讲,上述大多数建议都不是 C++,而是 C 解决方案。
查看 std::stringstream 的使用。
Most of the above suggestions technically aren't C++, they're C solutions.
Look into the use of std::stringstream.