45 使用库函数将数字转换为字符串,下面是常用库函数

(1) itoa():将整型转换为字符串

(2)ltoa():将长整形转换为字符串

(3)gcvt():将浮点转换为字符串

46 不使用库函数将整数转换为字符串

-------->通过把整数的各位上的数字加上'\0'转换为char类型并存到字符数组

(1)代码

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void int2str(int n, char *str)
 5 {
 6     char buf[10] = "";
 7     int i = 0;
 8     int len = 0;
 9     int temp = n < 0 ? -n : n;//绝对值
10 
11     if (str == NULL)
12     {
13         return;
14     }
15     while (temp)
16     {
17         buf[i++] = (temp % 10) + '\0';
18         temp = temp / 10;
19     }
20     len = n < 0 ? ++i : i;//如果n是负数 需要多一位来存放负数
21     str[i] = 0;
22     while (1)
23     {
24         i--;
25         if (buf[len - i - 1] == 0)
26         {
27             break;
28         }
29         str[i] = buf[len - i - 1];//buf数组里的字符拷到字符串
30         if (i == 0)
31         {
32             str[i] = '-';
33         }
34     }
35 
36 }
37 
38 int main2()
39 {
40     int nNum;
41     char p[10];
42 
43     cout << "please input an integer";
44     cin >> nNum;
45     cout << "output";
46     int2str(nNum, p);
47     cout << p << endl;
48 
49 
50     return 1;
51 }
View Code

相关文章:

  • 2021-11-08
  • 2021-09-25
  • 2022-12-23
  • 2021-11-19
猜你喜欢
  • 2021-12-06
  • 2021-07-31
  • 2022-12-23
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2021-05-31
相关资源
相似解决方案