将整数变为字符串的函数c语言,编写程序将整数转换为字符串

定义一个函数以返回整数的字符串表示形式。整数作为参数传递。例如,如果参数为25,则函数将返回:"25"。如果参数是-98,则函数将返回"-98"。

实现代码

#include

#include

#define STR_LEN 6 // 存储值字符串的字符串长度

char* itoa(int n, char str[], size_t size) {

size_t i = 0; // character count

bool negative = n < 0; // Indicates negative integer

int length = 0; // Length of string

char temp = '0'; // Temporary storage

if (negative) // If it's negative...

n = -n; // make it positive

// Generate digit characters in reverse order

do

{

if (size == i + 1 + (negative ? 1 : 0))

{

printf("String not long enough.\n");

return NULL;

}

str[i++] = '0' + n % 10; // Create a rightmost digit

n /= 10; // Remove the digit

} while (n > 0); // Go again if there's more digits

if (negative) // If it was negative...

str[i++] = '-'; // ...append minus

str[i] = '\0'; // Append terminator

length = i; // Save the length including null character

// Now reverse the string in place by switching first and last,

// second and last but one, third and last but two, etc.

for (i = 0; i < length / 2; ++i)

{

temp = str[i];

str[i] = str[length - i - 1];

str[length - i - 1] = temp;

}

return str; // Return the string

}

int main(void)

{

char str[STR_LEN]; // 存储整数的字符串表示形式

long testdata[] = { 3L, -98L, 110L, -1L, 999L, -12345L, 12345L };

for (int i = 0; i < sizeof testdata / sizeof(long); ++i)

{

if (itoa(testdata[i], str, sizeof(str)))

printf("Integer value is %d, string is %s\n", testdata[i], str);

}

system("pause");

return 0;

}

执行上面示例代码,得到以下结果:

Integer value is 3, string is 3

Integer value is -98, string is -98

Integer value is 110, string is 110

Integer value is -1, string is -1

Integer value is 999, string is 999

String not long enough.

Integer value is 12345, string is 12345

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值