函数重写-int和字符串互相转化

 int转字符串和/字符串int转

注意:指针作为形参一定要检测是否为空

           int转字符串市,注意负数

            字符串转int,注意空格和正负号

  代码:

#include <iostream>
#include <ctype.h>
#include <stdio.h>
#include <assert.h>

using namespace std;

//int转字符串
void itoa(int x, char *p)
{
	int sign = 1, i = 0; 
	char *str=p; //保存头地址
	if (x < 0)
	{
		x = -x;
		sign = -1;
		i++;
	}

	do {
		str[i++] = x % 10 + '0';//取下一个数字
	} while ((x /= 10) > 0);//删除该数字

	if (sign == -1)
	{
		str[0] = '-';
	}

	str[i]='\0';

	for (int j = i; j >= 0; j--)//生成的数字是逆序的,所以要逆序输出
		printf("%c", str[j]);
}

//字符串转int
int atoi(char *str)
{
	assert(str != NULL);
	int i = 0, n = 0, sign;
	while (isspace(str[i]))
	{
		i++;
	}

	if (str[i] == '+')//跳过符号
	{
		i++;
		sign = 1;
	}

	if (str[i] == '-')//跳过符号
	{
		i++;
		sign = -1;
	}

	for (n = 0; isdigit(str[i]); i++)
		n = 10 * n + (str[i] - '0');       //将数字字符转换成整形数字

	return sign * n;
}

int main()
{
	cout << "run my code!" << endl;
	int num = -966666;
	char str[100];
	itoa(num,str);
	printf("%s\n", str);

	char *str2 = "-33333";
	int  data = atoi(str2);
	cout << "data:" << data << endl;

	getchar();
	return 0;
}

运行结果:

猜你喜欢

转载自blog.csdn.net/weixin_39752599/article/details/105860042