C++的string库没有提供一个方便的像string.int()这样转整形的函数,因此整理了几个转化的方法:
// 非标准函数,所以自己实现了个
char * itoa(int n , char * res, int size);
int main()
{
int i = 1984;
string str;
/*********************
* integer -> string *
*********************/
// method 1: stringstream
ostringstream oss;
oss << i;
str = oss.str();
cout << "Method 1: " << str << endl;
// method 2: non-standard function,
char buf[10];
itoa(i, buf, 10);
str = buf;
cout << "Method 2: " << str << endl;
// method 3: sprintf
int ret = sprintf(buf, "%d", i);
str = buf;
cout << "Method 3: " << str << endl;
/*********************
* string -> integer *
*********************/
// method 1: stringstream
istringstream iss(str);
iss >> i;
cout << "Method 1: " << i << endl;
// method 2: atoi
i = atoi(str.c_str());
cout << "Method 2: " << i << endl;
// method 3: sscanf
sscanf(buf, "%d", &i);
cout << "Method 3: " << i << endl;
return 0;
}
char * itoa(int n , char * res, int size)
{
char * p = res;
if (n != 0 && p - res < size) {
p = itoa(n / 10, p, size - 1);
* p = n % 10 + '0';
++p;
* p = '/0';
}
return p;
}