1 前言
其实在源代码中int本身也要用一串字符表示,前后没有双引号,告诉编译器把它当作一个数解释。缺省情况下,是当成10进制(dec)来解释,如果想用8进制,16进制,怎么办?加上前缀,告诉编译器按照不同进制去解释。8进制(oct)—前缀加0,16进制(hex)—前缀加0x或者0X。string前后加上双引号,告诉编译器把它当成一串字符来解释。
2 int转化为string或者char*
2.1 to_string函数
c++11标准增加了全局函数std::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);
Demo
// to_string example
#include <iostream> // std::cout
#include <string> // std::string, std::to_string
int main ()
{
std::string pi = "pi is " + std::to_string(3.1415926);
std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
std::cout << pi << '\n';
std::cout << perfect << '\n';
return 0;
}
Output
pi is 3.141593
28 is a perfect number
2.2 使用itoa(int value, char *string, int radix)
将int整型数转化为一个字符串,并将值保存在数组string.其中value为要转化的整数, radix是基数的意思,即先将value转化为radix进制的数,之后再保存在string中.
char *itoa( int value, char *string,int radix);
参数列表:
value:欲转换的数据。
string:目标字符串的地址。
radix:转换后的进制数,可以是10进制、16进制等。
返回指向string这个字符串的指针
int aa = 30;
char c[8];
itoa(aa,c,16);
cout<<c<<endl; // 1e
注意: itoa并不是一个标准的C函数,应尽量避免使用这个函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。
2.3 使用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); //X表示读入或输出十六进制串
cout<<c<<endl; // 0001E
2.4 使用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的类型,吐出不同的类型。
2.5 使用boost库中的lexical_cast
int aa = 30;
string s = boost::lexical_cast<string>(aa);
cout<<s<<endl; // 30
2.4和2.5只能转化为10进制的字符串,不能转化为其它进制的字符串。
3 string转化为int
3.1 使用strtol(string to long)
Standard C 语言标准函数库速查 (Cheat Sheet)http://ganquan.info/standard-c/function/strtol
long int strtol(const char *nptr, char **endptr, int base)
strtol()会将nptr指向的字符串,根据参数base,按权转化为long int, 然后返回这个值。参数base的范围为2~36,和0;它决定了字符串以被转换为整数的权值。strtol()函数检测到第一个非法字符时,立即停止检测,其后的所有字符都会被当作非法字符处理。合法字符串会被转换为long int, 作为函数的返回值。非法字符串,即从第一个非法字符的地址,被赋给endptr。**endptr是个双重指针,即指针的指针。strtol()函数就是通过它改变endptr的值,即把第一个非法字符的地址传给endptr。多数情况下,endptr设置为NULL, 即不返回非法字符串。
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
3.2 使用sscanf
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.3 使用stringstream
string s = "17";
stringstream ss;
ss<<s;
int i;
ss>>i;
cout<<i<<endl; // 17
注: stringstream可以吞下任何类型,根据实际需要吐出不同的类型。
3.4 使用boost库中的lexical_cast
string s = "17";
int i = boost::lexical_cast<int>(s);
cout<<i<<endl; // 17