itoa
函數是一個非標準的函數,主要在一些舊的 C++ 庫和編譯器中使用
std::to_string
:#include<iostream>
#include<string>
int main() {
int num = 42;
std::string str = std::to_string(num);
std::cout << "Number: "<< num << ", String: "<< str<< std::endl;
return 0;
}
std::ostringstream
:#include<iostream>
#include <sstream>
#include<string>
int main() {
int num = 42;
std::ostringstream oss;
oss<< num;
std::string str = oss.str();
std::cout << "Number: "<< num << ", String: "<< str<< std::endl;
return 0;
}
std::snprintf
:#include<iostream>
#include <cstdio>
#include<string>
int main() {
int num = 42;
char buffer[20]; // 足夠大以容納整數
std::snprintf(buffer, sizeof(buffer), "%d", num);
std::string str(buffer);
std::cout << "Number: "<< num << ", String: "<< str<< std::endl;
return 0;
}
這些方法都可以實現將整數轉換為字符串,并且在現代 C++ 編程中更常用。使用這些方法而不是 itoa
可以確保你的代碼更具可移植性和兼容性。