阅读量:79
itoa 函数是一个非标准的函数,主要在一些旧的 C++ 库和编译器中使用
- 使用
std::to_string:
#include
#include
int main() {
int num = 42;
std::string str = std::to_string(num);
std::cout << "Number: "<< num class="hljs-string">", String: "<< str class="hljs-keyword">return 0;
}
- 使用
std::ostringstream:
#include
#include
#include
int main() {
int num = 42;
std::ostringstream oss;
oss<< num xss=removed class="hljs-built_in">str();
std::cout << "Number: "<< num class="hljs-string">", String: "<< str class="hljs-keyword">return 0;
}
- 使用
std::snprintf:
#include
#include
#include
int main() {
int num = 42;
char buffer[20]; // 足够大以容纳整数
std::snprintf(buffer, sizeof(buffer), "%d", num);
std::string str(buffer);
std::cout << "Number: "<< num class="hljs-string">", String: "<< str class="hljs-keyword">return 0;
}
这些方法都可以实现将整数转换为字符串,并且在现代 C++ 编程中更常用。使用这些方法而不是 itoa 可以确保你的代码更具可移植性和兼容性。