c++ int与string的转换

int转化为string

1、使用itoa(int to string)

//char *itoa( int value, char *string,int radix);
// 原型说明:
// value:欲转换的数据。
// string:目标字符串的地址。
// radix:转换后的进制数,可以是10进制、16进制等。
// 返回指向string这个字符串的指针

int a = 30;
char b[8];
itoa(a,b,16);
cout<<c<<endl;

注意:itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。

2、使用sprintf

// int sprintf( char *buffer, const char *format, [ argument] … );
//参数列表
// buffer:char型指针,指向将要写入的字符串的缓冲区。
// format:格式化字符串。
// [argument]...:可选参数,可以是任何类型的数据。
// 返回值:字符串长度(strlen)

int aa = 30;
char c[8]; 
int length = sprintf(c, "%05X", aa); 
cout<<c<<endl; // 0001E

3、使用stringstream

int aa = 30;
stringstream ss;
ss<<aa; 
string s1 = ss.str();
cout<<s1<<endl; // 30

string s2;
ss>>s2;
cout<<s2<<endl; // 30

可以这样理解,stringstream可以吞下不同的类型,根据s2的类型,然后吐出不同的类型。
4、使用boost库中的lexical_cast

int aa = 30;
string s = boost::lexical_cast<string>(aa);
cout<<s<<endl; // 30

3和4只能转化为10进制的字符串,不能转化为其它进制的字符串。

5、to_string函数

这是C++11新增的,使用非常方便,简单查了下:C++11标准增加了全局函数std::to_string,

to_string这个函数还是很强大的!

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val)

string转int

string转化为int
1、使用strtol(string to long) 

string s = "17";
char* end;
int i = static_cast<int>(strtol(s.c_str(),&end,16));
cout<<i<<endl; // 23

i = static_cast<int>(strtol(s.c_str(),&end,10));
cout<<i<<endl; // 17

2、使用sscanf

扫描二维码关注公众号,回复: 2821498 查看本文章
int i;
sscanf("17","%D",&i);
cout<<i<<endl; // 17

sscanf("17","%X",&i);
cout<<i<<endl; // 23

sscanf("0X17","%X",&i);
cout<<i<<endl; // 23

3、使用stringstream

string s = "17";

stringstream ss;
ss<<s;

int i;
ss>>i;
cout<<i<<endl; // 17

注:stringstream可以吞下任何类型,根据实际需要吐出不同的类型。
4、使用boost库中的lexical_cast

string s = "17";
int i = boost::lexical_cast<int>(s);
cout<<i<<endl; // 17

5、std::stoi/stol/stoll等等函数

猜你喜欢

转载自blog.csdn.net/mikasoi/article/details/81637438