您的位置:首页 > 编程语言 > C语言/C++

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

2014-08-09 21:13 411 查看
/**************************************************
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: