最简单的方法是使用一个字符串流(stringstream),整形转成字符串
下面的string类型应该是STL中string。
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
string itos(int i) // 将int 转换成string{
stringstream s;
s << i;
return s.str();
}
int main(){
int i = 127;
string ss = itos(i);
const char* p = ss.c_str();
cout << ss << " " << p << "\n";
}
自然地,这种技术能够将任何使用<<输出的类型转换为字符串。
常规操作
一、atoi()——把字符串转换成整型数
C++实现:
#include <iostream>
using namespace std;
int str2int(const char *str)
{
int temp = 0;
const char *ptr = str; //ptr保存str字符串开头
if (*str == '-' || *str == '+') //如果第一个字符是正负号,
{ //则移到下一个字符
str++;
}
while(*str != 0)
{
if ((*str < '0') || (*str > '9')) //如果当前字符不是数字
{ //则退出循环
break;
}
temp = temp * 10 + (*str - '0'); //如果当前字符是数字则计算数值
str++; //移到下一个字符
}
if (*ptr == '-') //如果字符串是以“-”开头,则转换成其相反数
{
temp = -temp;
}
return temp;
}
int main()
{
int n = 0;
char p[10] = "";
cin.getline(p, 20); //从终端获取一个字符串
n = str2int(p); //把字符串转换成整型数
cout << n << endl;
return 0;
}
二、itoa()——把一整数转换为字符串
C++实现:
#include <iostream>
#include "stdio.h"
#include "string"
using namespace std;
void int2str(int n, char *str)
{
char buf[10] = "";
int i = 0;
int len = 0;
int temp = n < 0 ? -n: n; // temp为n的绝对值
if (str == NULL)
{
return;
}
while(temp)
{
buf[i++] = (temp % 10) + '0'; //把temp的每一位上的数存入buf
temp = temp / 10;
}
len = n < 0 ? ++i: i; //如果n是负数,则多需要一位来存储负号
str[i] = 0; //末尾是结束符0
while(1)
{
i--;
if (buf[len-i-1] ==0)
{
break;
}
str[i] = buf[len-i-1]; //把buf数组里的字符拷到字符串
}
if (i == 0 )
{
str[i] = '-'; //如果是负数,添加一个负号
}
}
int main()
{
int nNum;
char p[10];
cout << "Please input an integer:";
cin >> nNum;
cout << "output: " ;
int2str(nNum, p); //整型转换成字符串
cout<< p << endl;
return 0;
}