#include <stdlib.h>
int a = 3;
long b = 23;
char buf1[30], buf2[30];
itoa(a, buf1, 10); // buf1 = "3"
ltoa(b, buf2, 10); // buf2 = "23"
第三參數為進制(10=十進制,16=十六進制等)。
#include <stdio.h>
int a = 3;
float b = 4.2f;
char buf[30];
sprintf(buf, "%d,%f", a, b); // buf = "3,4.200000"
格式控制同 printf,支持寬度、精度、進制等豐富格式。
#include <sstream>
#include <string>
using namespace std;
int a = 3;
float b = 4.2f;
ostringstream oss;
oss << a << "," << b;
string s = oss.str(); // s = "3,4.2"
類似 cout,自動處理類型轉換,無格式字符串風險。
#include <stdlib.h>
int a = atoi("32");
long b = atol("333");
double c = atof("23.4");
轉換失敗返回 0,無法區分 "0" 與非法輸入。
#include <stdlib.h>
char *endptr;
long b = strtol("333", &endptr, 10); // 10=十進制
double c = strtod("32.3", &endptr);
endptr 指向首個未轉換字符,可檢測輸入合法性。
#include <stdio.h>
int a; float b;
sscanf("23 23.4", "%d %f", &a, &b);
返回成功轉換項數,支持複雜格式匹配。
#include <sstream>
#include <string>
using namespace std;
int a; float b;
istringstream iss("23 23.4");
iss >> a >> b;
可檢查流狀態 iss.fail() 判斷轉換成敗。
| 場景 | 推薦方法 | 理由 |
|---|---|---|
| C代碼、簡單整數轉字符串 | itoa / sprintf | 輕量、兼容性好 |
| C++代碼、追求類型安全 | ostringstream / istringstream | 無格式字符串漏洞、自動類型推導 |
| 需要錯誤檢查、進制轉換 | strtol / strtod | 標準庫提供完整錯誤信息 |
| 複雜格式解析 | sscanf | 格式字符串表達力強 |
%.2f 控制to_string / stoi 等更現代化接口