用于将整数转换为字符串 C++ 的 itoa() 的替代方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/228005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alternative to itoa() for converting integer to string C++?
提问by Tomek
I was wondering if there was an alternative to itoa()
for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.
我想知道是否有itoa()
将整数转换为字符串的替代方法,因为当我在 Visual Studio 中运行它时,我收到警告,而当我尝试在 Linux 下构建我的程序时,我收到一个编译错误。
回答by spoulson
In C++11 you can use std::to_string
:
在 C++11 中,您可以使用std::to_string
:
#include <string>
std::string s = std::to_string(5);
If you're working with prior to C++11, you could use C++ streams:
如果您使用的是 C++11 之前的版本,则可以使用 C++ 流:
#include <sstream>
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
取自http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
回答by Leon Timmermans
boost::lexical_castworks pretty well.
boost::lexical_cast效果很好。
#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
std::string foo = boost::lexical_cast<std::string>(argc);
}
回答by paercebal
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
itoa 是一个非标准的辅助函数,旨在补充 atoi 标准函数,并且可能隐藏了一个 sprintf(它的大部分功能都可以在 sprintf 方面实现):http: //www.cplusplus.com/reference/clibrary/cstdlib/ itoa.html
The C Way
C方式
Use sprintf. Or snprintf. Or whatever tool you find.
使用 sprintf。或者snprintf。或者你找到的任何工具。
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).
尽管事实上有些函数不在标准中,正如“onebyone”在他的评论中正确提到的那样,大多数编译器都会为您提供替代方案(例如,Visual C++ 有自己的 _snprintf,如果需要,您可以将其 typedef 为 snprintf)。
The C++ way.
C++方式。
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).
使用 C++ 流(在当前情况下是 std::stringstream(甚至是不推荐使用的 std::strstream,正如 Herb Sutter 在他的一本书中所提出的,因为它有点快)。
Conclusion
结论
You're in C++, which means that you can choose the way you want it:
您使用的是 C++,这意味着您可以选择您想要的方式:
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).
更快的方式(即 C 方式),但您应该确保代码是应用程序中的瓶颈(过早的优化是邪恶的,等等)并且您的代码被安全地封装以避免缓冲区溢出的风险。
更安全的方式(即 C++ 方式),如果您知道这部分代码并不重要,那么最好确保这部分代码不会在随机时刻中断,因为有人误认为了大小或指针(这种情况会发生)在现实生活中,就像......昨天,在我的电脑上,因为有人认为使用更快的方式而不真正需要它“很酷”)。
回答by Jeremy Ruten
Try sprintf():
试试 sprintf():
char str[12];
int num = 3;
sprintf(str, "%d", num); // str now contains "3"
sprintf() is like printf() but outputs to a string.
sprintf() 与 printf() 类似,但输出为字符串。
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:
此外,正如 Parappa 在评论中提到的,您可能希望使用 snprintf() 来阻止缓冲区溢出的发生(您正在转换的数字不适合您的字符串的大小。)它的工作原理是这样的:
snprintf(str, sizeof(str), "%d", num);
回答by 1800 INFORMATION
Behind the scenes, lexical_cast does this:
在幕后, lexical_cast 这样做:
std::stringstream str;
str << myint;
std::string result;
str >> result;
If you don't want to "drag in" boost for this, then using the above is a good solution.
如果您不想为此“拖入”提升,那么使用上述方法是一个很好的解决方案。
回答by Tag318
We can define our own iota
function in c++ as:
我们可以iota
在 C++ 中定义我们自己的函数:
string itoa(int a)
{
string ss=""; //create empty string
while(a)
{
int x=a%10;
a/=10;
char i='0';
i=i+x;
ss=i+ss; //append new character at the front of the string!
}
return ss;
}
Don't forget to #include <string>
.
不要忘记#include <string>
。
回答by Vasaka
С++11 finally resolves this providing std::to_string
.
Also boost::lexical_cast
is handy tool for older compilers.
С++11 终于解决了这个提供std::to_string
. 也是boost::lexical_cast
旧编译器的方便工具。
回答by jm1234567890
I use these templates
我使用这些模板
template <typename T> string toStr(T tmp)
{
ostringstream out;
out << tmp;
return out.str();
}
template <typename T> T strTo(string tmp)
{
T output;
istringstream in(tmp);
in >> output;
return output;
}
回答by dcw
Try Boost.Formator FastFormat, both high-quality C++ libraries:
试试Boost.Format或FastFormat,两者都是高质量的 C++ 库:
int i = 10;
std::string result;
WIth Boost.Format
使用 Boost.Format
result = str(boost::format("%1%", i));
or FastFormat
或快速格式化
fastformat::fmt(result, "{0}", i);
fastformat::write(result, i);
Obviously they both do a lot more than a simple conversion of a single integer
显然,他们都做的不仅仅是单个整数的简单转换
回答by Mark Renslow
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.
您实际上可以使用一个巧妙编写的模板函数将任何内容转换为字符串。此代码示例使用循环在 Win-32 系统中创建子目录。字符串连接运算符 operator+ 用于将根与后缀连接以生成目录名称。后缀是通过使用模板函数将循环控制变量 i 转换为 C++ 字符串并将其与另一个字符串连接来创建的。
//Mark Renslow, Globe University, Minnesota School of Business, Utah Career College
//C++ instructor and Network Dean of Information Technology
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream> // string stream
#include <direct.h>
using namespace std;
string intToString(int x)
{
/**************************************/
/* This function is similar to itoa() */
/* "integer to alpha", a non-standard */
/* C language function. It takes an */
/* integer as input and as output, */
/* returns a C++ string. */
/* itoa() returned a C-string (null- */
/* terminated) */
/* This function is not needed because*/
/* the following template function */
/* does it all */
/**************************************/
string r;
stringstream s;
s << x;
r = s.str();
return r;
}
template <class T>
string toString( T argument)
{
/**************************************/
/* This template shows the power of */
/* C++ templates. This function will */
/* convert anything to a string! */
/* Precondition: */
/* operator<< is defined for type T */
/**************************************/
string r;
stringstream s;
s << argument;
r = s.str();
return r;
}
int main( )
{
string s;
cout << "What directory would you like me to make?";
cin >> s;
try
{
mkdir(s.c_str());
}
catch (exception& e)
{
cerr << e.what( ) << endl;
}
chdir(s.c_str());
//Using a loop and string concatenation to make several sub-directories
for(int i = 0; i < 10; i++)
{
s = "Dir_";
s = s + toString(i);
mkdir(s.c_str());
}
system("PAUSE");
return EXIT_SUCCESS;
}