int转string
void intToStr(int number,char str[]) //10进制
{
int j = 0;
if (number == 0) //0值 返回空串
{
str[j] = '\0';
return;
}
int sign = number,i=0; //记录符号
char buf[10]="\0";
if (sign < 0) number = -number; //改成正数
while (number) {
buf[i++] = number % 10 + '0';
number /= 10;
}
if (sign < 0) {
str[j] = '-';
j++;
}
while (i>=0) {
str[j++] = buf[--i];
}
}
void main() {
int number;
char str[12]="\0";
cout << "请输入数字:";
cin >> number;
intToStr(number, str);
cout << "字符串是:" << str<<endl;
system("pause");
}
string 转int
int strToInt(const char * str) {
int temp = 0;
const char*ptr=str; //记录符号
if (*str == '-' || *str == '+') {
str++; //跳过符号
}
while (*str != '\0') {
if (*str > '9' || *str < '0') {
str++; continue;
}
temp = temp * 10 + (*str - '0');
str++;
}
if (*ptr == '-') {//根据记录的符号 还原
temp = -temp;
}
return temp;
}
void main() {
char * name = "-456zhang123";
int number = strToInt(name);
cout << number << endl;
system("pause");
}