int转string/ string 转Int

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");
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值