本文总结了几种把int转化成string的方法,为了方便,一些说明都放在了代码注释里,所以直接上代码。
#include "stdafx.h"
#include <iostream>
using namespace std;
#define CALL(namespace, method) \
{\
cout << "Calling " #namespace"::" #method ":"<< endl;\
method;\
}
#pragma region Convertto string
namespace CTS
{
int i = 199;
long l = 1999;
float f = 199.9f;
string s;
}
#define USECTSusing namespace CTS
// C++11, to_string
#include <string>
void TestToString()
{
USECTS;
cout << to_string(i) << endl << to_string(l) << endl << to_string(f) << endl; // 对于f, to_string会失真
}
// Stream
#include <sstream>
void TestSStream()
{
USECTS;
// stringstream
stringstream stream;
stream << i;
stream >> s;
cout << s << endl<< stream.str() << endl;
//ostringstream
ostringstream ostream;
ostream.str("hello");
ostream << i;
cout << ostream.str() << endl; // 结果是199lo, ostream <<从头开始将传入的数据输出到流
ostream.str("hello");
ostream << l;
cout << ostream.str() << endl;
ostream.str(""); // void str()将字符串拷贝到ostream,所以可以用来清空ostream
ostream << f;
cout << ostream.str() << endl;
}
// char[]: _itoa_s不是标准的C函数,是WINDOWS特有的,所以不能跨平台使用
void TestCharArray()
{
USECTS;
char c[8];
_itoa_s(i, c, 10); // 转换后的进制数是10进制
cout << c << endl;
}
//sprintf
void TestSprintf()
{
USECTS;
char c[8];
sprintf_s(c, "%d", i); // sprintf_s相对sprintf仅仅检查format或者缓冲区是否为空指针而言,
// 它对格式化的字符有效性也进行了检查。如果字符串过大,它会返回一个空string和设置无效参数句柄为激活。所以缓冲区不够大的时候会失败。
cout << c << endl;
}
//boost::lexical_cast
#include <boost/lexical_cast.hpp>
void TestBoostLexicalCast()
{
USECTS;
cout << boost::lexical_cast<string>(i)<< endl;
}
void TestConvertToString()
{
CALL(, TestToString());
CALL(, TestSStream());
CALL(, TestCharArray());
CALL(, TestSprintf());
CALL(, TestBoostLexicalCast());
}