c++转换整数为字符串步骤
1、 判断输入正负,并存储符号
2、 将输入整数从低位到高位存储到字符串指针中
3、 反转字符串
程序
关键步骤都在程序中进行了注释,以下程序能在vs2015社区版中直接执行,程序如下
#include <iostream>
#include <string>
using namespace std;
void itostr(char*, int);
void reverse(char*);
void itostr(char *str, int n)
{
int sign;
char *strtmp = str; //存储字符串起始位置
if (0 > (sign = n)) //判断数值是否为负,并存储符号
n = -n;
do //利用ASCII码将数值从低到高存储到字符串中
{
*str++ = n % 10 + '0';//这里的'0'我认为是将整数强制转换为字符串
} while ((n /= 10) > 0);
if (sign < 0) //如果符号为负则在字符串后添加负号
*str++ = '-';
*str = '\0'; //设置字符串结束符号
reverse(strtmp); //调用reverse函数反转字符串
}
void reverse(char *str) //reverse函数功能为反转字符串
{
char *t;
int c;
t = str + (strlen(str)) -1; //记录字符串末尾的内存地址
for (t; str < t; str++,t--)//str为第一个地址向右移动,t为末始地址向左移动,利用循环将字符串反转
{
c = *str; // 将str当前地址对应的内容赋值给c
*str = *t; //将当前地址t中的内容赋值给str
*t = c; //将c的内容赋值给*t
}
}
void main()
{
int n;
char str[40];
cout << "输入数字:";
cin >> n;
itostr(str, n);
cout << "转换为字符串:" << str << endl;
}