int转化成string

4 篇文章 0 订阅

本文总结了几种把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());

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值