C++ int转换为string

admin2025-12-04 10:12:14779

我们可以使用 C 标准库或C++库函数/类将 int 转换为字符串。

"现代"C++风格的方式

我们可以使用C++标准库中的std::to_string(), 这个是自11年以来添加到C++标准库中的。如果项目使用C++ 11 和之后的标准,建议使用这个方法。

std::string to_string( int value );

在标准头中定义,将数值转换为 std::string。

1) 具有与 std::sprintf(buf、"%d",value)一样,将带符号的十进制整数转换为将生成字符串的功能。

用于C++的一个程序示例如下。

std::to_string()

#include

#include

int main ()

{

int n = 123;

std::string str = std::to_string(n);

std::cout << n << " ==> " << str << std::endl;

return 0;

}

请注意,可能会从构造函数抛出异常。如果调用方打算处理这个异常,则调用方可能需要捕获下面的异常。

std::to_string() std::bad_allocstd::string

基于C++样式的流

我们可以使用C++库 std::stringstream,它已可用于 C++11之前将 int 转换为字符串。使用C++程序的一个如下。

std::stringstream

#include

#include

int main()

{

int i = 123;

std::stringstream ss;

ss << i;

std::string out_string = ss.str();

std::cout << out_string << "\n";

return 0;

}

C 样式方式

我们还可以在应用程序中使用 C 标准C++函数。一个C标准库函数,可以执行 int 到字符串转换的函数snprintf()。

#include

int snprintf(char *str, size_t size, const char *format, ...);

The functions snprintf() and vsnprintf() write at most size bytes (including the terminating null byte ('\0')) to str.

下面是C++中使用函数将 int 转换为字符串的一个例子。

snprintf()

#include

#include

#define MAX_BUFFER_SIZE 128

int main()

{

int number = 123;

char out_string [MAX_BUFFER_SIZE];

int rt = snprintf(out_string, MAX_BUFFER_SIZE, "%d", number);

if (rt < 0) {

std::cerr << "snprintf() failed with return code " << rt << std::endl;

} else {

std::cout << "out_string = \"" << out_string << "\"\n";

}

return 0;

}

参考资料:

https://www.systutorials.com/how-to-convert-int-to-string-in-cpp/