c++中 int 和 string 的相互转换

/**************************************************
author: Andrewseu
date: 2014.8.8
**************************************************/
#include<iostream>
#include<string>
#include<strstream>
using namespace std;

int main()
{
	/*************************************************
	string 转int:
	方法一:int atoi( const char *str );
	功能:功能:将字符串str转换成一个整数并返回结果。
	参数str 以数字开头,当函数从str 中读到非数字字符则
	结束转换并将结果返回

	方法二:std:to_string();
	*************************************************/
	//方法一
	cout << "stringtoInt:" << atoi("1223243") << endl;
	string s = "45454";
	cout << atoi(s.c_str()) << endl;
	//方法二
	cout << std::to_string(43) << endl;


	/*****************************************************
	int 转 string:
	方法一:itoa已经deprecation了,用_itoa;
	方法一: int sprintf( char *buffer, const char *format, ... );
	sprintf()函数和printf()类似, 只是把输出发送到buffer(缓冲区)
	中.返回值是写入的字符数量
	方法三:strstream
	*****************************************************/
	//方法一:
	int test = 1234;
	char * cs = "sd";
	char carray[20];
	cout << _itoa(test,carray,10) << endl;

	//方法二:
	cout << sprintf(carray,"%d",test) << endl;
	string charString = carray;
	cout << charString << endl;

	//方法三:
	strstream strstr;
	string ss;
	strstr << test;
	strstr >> ss;
	cout << ss << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值