整数转换为字符串的两种方法

1.使用itoa函数

itoa()函数

itoa()原型:  char *itoa( int value, char *string,int radix);

原型说明:

输入参数:

value:要转换的数据。
string:目标字符串的地址。
radix:转换后的进制数,可以是10进制、16进制等,范围必须在 2-36。

功能:将整数value 转换成字符串存入string 指向的内存空间 ,radix 为转换时所用基数(保存到字符串中的数据的进制基数)。

返回值:函数返回一个指向 str,无错误返回。

注意:itoa不是一个标准的c函数,他是windows特有的,跨平台写程序,要用sprintf。

实现方法:

#include "stdafx.h"
#include<stdio.h>
#include"stdlib.h"
#include<iostream>
#include<ctype.h>
using namespace std;
int main()
{
	int number = 12345;
	char stri[7];
	_itoa_s(number,stri,10);
	cout <<number<<" "<<stri<<endl;
	system("pause");

	return 0;
	
	
}

2.采用加’0‘再逆序的方法

实现方法

#include "stdafx.h"
#include<iostream>
#include<stdio.h>

int main()
{
	int num = 12345, j = 0, i = 0;
	char temp[7], str[7];
	while (num)
	{
		temp[i] = num % 10 + '0';
		i++;
		num = num / 10;
	}
	temp[i] = 0;
	printf("temp=%s\n",temp);
	i = i - 1;
	printf("temp=%d\n",i);
	while (i >= 0)
	{
		str[j] = temp[i];
		i--;
		j++;
	}
	str[j] = '\0';
	printf("string=%s\n",str);
	system("pause");
	return 0;
	
	
}

  • 18
    点赞
  • 72
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值