Yoc*_*mer 331
您可以在C++ 11中使用std :: to_string
int i = 3;
std::string str = std::to_string(i);
Run Code Online (Sandbox Code Playgroud)
Ben*_*oit 47
#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());
Run Code Online (Sandbox Code Playgroud)
ltj*_*jax 36
boost::lexical_cast<std::string>(yourint) 从 boost/lexical_cast.hpp
使用std :: ostream支持一切工作,但速度不快,例如, itoa
它甚至看起来比stringstream或scanf更快:
neu*_*uro 30
众所周知的方法是使用stream运算符:
#include <sstream>
std::ostringstream s;
int i;
s << i;
std::string converted(s.str());
Run Code Online (Sandbox Code Playgroud)
当然,您可以使用模板函数^^将其概括为任何类型
#include <sstream>
template<typename T>
std::string toString(const T& value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
Run Code Online (Sandbox Code Playgroud)
Zac*_*and 14
非标准功能,但它在大多数常见编译器上实现:
int input = MY_VALUE;
char buffer[100] = {0};
int number_base = 10;
std::string output = itoa(input, buffer, number_base);
Run Code Online (Sandbox Code Playgroud)
更新
C++ 11引入了几个std::to_string重载(注意它默认为base-10).
use*_*016 14
如果您无法std::to_string在C++ 11中使用,可以按照cppreference.com上的定义编写它:
std::string to_string( int value )将带符号的十进制整数转换为具有与std::sprintf(buf, "%d", value)足够大的buf所产生的内容相同的内容的字符串.
履行
#include <cstdio>
#include <string>
#include <cassert>
std::string to_string( int x ) {
int length = snprintf( NULL, 0, "%d", x );
assert( length >= 0 );
char* buf = new char[length + 1];
snprintf( buf, length + 1, "%d", x );
std::string str( buf );
delete[] buf;
return str;
}
Run Code Online (Sandbox Code Playgroud)
你可以用它做更多的事情.只是用于"%g"将float或double转换为字符串,用于"%x"将int转换为十六进制表示,依此类推.
下面的宏并不像一个一次性使用的紧凑型ostringstream或boost::lexical_cast.
但是如果你需要在代码中重复转换为字符串,那么这个宏在使用上比直接处理字符串流或每次显式转换都更优雅.
它也非常通用,因为它可以转换所有支持的东西operator<<(),甚至可以组合使用.
定义:
#include <sstream>
#define SSTR( x ) dynamic_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
Run Code Online (Sandbox Code Playgroud)
说明:
这std::dec是一种无副作用的方法,可以将匿名ostringstream变为通用,ostream因此operator<<()函数查找可以适用于所有类型.(如果第一个参数是指针类型,则会遇到麻烦.)
在dynamic_cast返回式回ostringstream,所以你可以调用str()它.
使用:
#include <string>
int main()
{
int i = 42;
std::string s1 = SSTR( i );
int x = 23;
std::string s2 = SSTR( "i: " << i << ", x: " << x );
return 0;
}
Run Code Online (Sandbox Code Playgroud)