C++中整数转换为字符串的方法

C++中整数转换为字符串的方法

技术背景

在C++编程中,将整数转换为字符串是一个常见的需求,比如在日志记录、用户界面显示等场景中。随着C++标准的不断发展,提供了多种不同的方法来实现这一转换。

实现步骤

C++11及以上

std::to_string

C++11引入了std::to_string函数,它是将整数转换为字符串的简洁方法。

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>

int main() {
int x = 1612;
std::string s = std::to_string(x);
std::cout << s << std::endl;
return 0;
}

std::format(C++20)

std::format是一种通用的格式化方法,支持多种格式说明符。

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <format>

int main() {
std::string d = std::format("{}", 100); // d = "100"
std::string h = std::format("{:#x}", 15); // h = "0xf"
std::cout << d << std::endl;
std::cout << h << std::endl;
return 0;
}

std::to_chars(C++17)

std::to_chars提供了高性能、无动态分配的转换方式。

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <array>
#include <utility>
#include <string_view>

int main() {
std::array<char, 5> a;
auto [ptr, ec] = std::to_chars(a.data(), a.data() + a.size(), 1234);
std::string_view view(a.data(), ptr);
std::cout << view << std::endl;
return 0;
}

旧版C++

std::ostringstream(C++98)

使用std::ostringstream可以将整数插入到流中,然后提取为字符串。

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <sstream>
#include <string>

int main() {
std::string d = (std::ostringstream() << 100).str(); // d = "100"
std::string h = (std::ostringstream() << std::hex << 15).str(); // h = "0xf"
std::cout << d << std::endl;
std::cout << h << std::endl;
return 0;
}

std::sprintf(C++98)

std::sprintf是C语言的格式化函数,在C++中也可以使用。

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdio>
#include <string>

int main() {
char a[20];
sprintf(a, "%d", 15); // a = {'1', '5', '\0', ?, ?, ?, ...}
std::string s = a;
std::cout << s << std::endl;
return 0;
}

Boost lexical_cast

如果安装了Boost库,可以使用lexical_cast进行类型转换。

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>

int main() {
int num = 4;
std::string str = boost::lexical_cast<std::string>(num);
std::cout << str << std::endl;
return 0;
}

最佳实践

  • 如果只是简单地将整数转换为十进制字符串,推荐使用std::to_string,它简洁且易于使用。
  • 如果需要高性能、无动态分配的转换,且使用C++17及以上标准,std::to_chars是更好的选择。
  • 如果需要更复杂的格式化功能,C++20的std::format是一个不错的选择。

常见问题

  • 使用std::ostringstream的问题:使用std::ostringstream进行转换时,可能会受到当前区域设置的影响,例如整数可能会添加千位分隔符。因此,在需要精确转换时,不建议使用。
  • std::to_chars的空终止符问题std::to_chars不会添加空终止符,需要手动处理。例如,可以使用std::string_view来处理没有空终止符的字符序列。

C++中整数转换为字符串的方法
https://119291.xyz/posts/cpp-int-to-string-conversion/
作者
ww
发布于
2025年5月20日
许可协议