实现一个函数itoa(int n, char s[]),将整数n这个数字转换为对应的字符串,保存到s中。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现一个函数itoa(int n, char s[]),将整数n这个数字转换为对应的字符串,保存到s中。相关的知识,希望对你有一定的参考价值。

实现一个函数itoa(int n, char s[]),将整数n这个数字转换为对应的字符串,保存到s中。

#include <stdio.h>

void reverse(char *left, char *right)
{
 while (left < right)
 {
  char tmp = *left;
  *left = *right;
  *right = tmp;
  left++;
  right--;
 }
}

void my_itoa(int n, char s[])
{
 char *start;
 char *end;
 if (n < 0)
 {
  *s = ‘-‘;
  n = -n;
  s++;
 }
 start = s;
 while (n)
 {
  *s = (n % 10) + ‘0‘;
  s++;
  n /= 10;
 }
 *s = ‘\0‘;
 end = s - 1;
 reverse(start, end);


}

int main()
{
 int num = -1234;
 char arr[10];
 my_itoa(num, arr);
 printf("%s\n", arr);
 return 0;
}


以上是关于实现一个函数itoa(int n, char s[]),将整数n这个数字转换为对应的字符串,保存到s中。的主要内容,如果未能解决你的问题,请参考以下文章

itoa() 的 C++ 标准替代方案,用于将 int 转换为以 10 为底的 char*

如何用c语言把整形转换成字符型

char*怎么转换string

c语言中,函数itoa有啥功能,怎么用

字符串函数---itoa()函数具体解释及实现

c++ uint32 如何转 const char