在C++中,itoa
函數并不是標準庫的一部分,因此建議使用其他替代方法
方法1:使用std::to_string
#include<iostream>
#include<string>
int main() {
int number = 42;
std::string str_number = std::to_string(number);
std::cout << "Number as string: "<< str_number<< std::endl;
return 0;
}
方法2:使用std::ostringstream
#include<iostream>
#include <sstream>
#include<string>
int main() {
int number = 42;
std::ostringstream oss;
oss<< number;
std::string str_number = oss.str();
std::cout << "Number as string: "<< str_number<< std::endl;
return 0;
}
方法3:自定義itoa函數
#include<iostream>
#include<string>
#include<algorithm>
std::string itoa_custom(int value, int base = 10) {
if (base < 2 || base > 36) {
throw std::invalid_argument("Invalid base");
}
if (value == 0) {
return "0";
}
char chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string result;
bool is_negative = value < 0;
if (is_negative) {
value = -value;
}
while (value != 0) {
int remainder = value % base;
result += chars[remainder];
value /= base;
}
if (is_negative) {
result += '-';
}
std::reverse(result.begin(), result.end());
return result;
}
int main() {
int number = 42;
std::string str_number = itoa_custom(number);
std::cout << "Number as string: "<< str_number<< std::endl;
return 0;
}
這些方法都可以實現將整數轉換為字符串。選擇最適合你需求的方法。