(筆記) 如何將int,double轉字串? (C/C++) (C)
Abstract
C語言並沒有提供一個函數專門將int, double轉字串,必須透過一個小技巧。
Introduction
有的compiler有提供itoa()與ltoa()將int, double轉字串,不過這些並非ANSI C標準,真正標準該使用sprintf()。
double_to_string.c / C
1 /*
2 (C) OOMusou 2008 http://oomusou.cnblogs.com
3
4 Filename : double_to_string.c
5 Compiler : Visual C++ 9.0 / Visual Studio 2008
6 Description : Demo how to convert string to int (double)
7 Release : 10/27/2008 1.0
8 */
9
10 #include <stdio.h>
11
12 int main() {
13 int i;
14 double d;
15 char s[256];
16
17 i = 10;
18 sprintf(s, "%d", i);
19 printf("%s\n", s);
20
21 d = 1.23;
22 sprintf(s, "%f", d);
23 printf("%s\n", s);
24 }
2 (C) OOMusou 2008 http://oomusou.cnblogs.com
3
4 Filename : double_to_string.c
5 Compiler : Visual C++ 9.0 / Visual Studio 2008
6 Description : Demo how to convert string to int (double)
7 Release : 10/27/2008 1.0
8 */
9
10 #include <stdio.h>
11
12 int main() {
13 int i;
14 double d;
15 char s[256];
16
17 i = 10;
18 sprintf(s, "%d", i);
19 printf("%s\n", s);
20
21 d = 1.23;
22 sprintf(s, "%f", d);
23 printf("%s\n", s);
24 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步