在 C++ 中将 int 转换为 string 的方法有:使用 to_string() 函数直接转换。使用 stringstream 类。使用 sprintf() 函数。

如何在 C++ 中将 int 转换为 string
直接转换法:
使用 to_string() 函数直接将 int 转换为 string。
<code class="cpp">#include <iostream>
#include <string>
int main() {
int number = 123;
std::string number_as_string = std::to_string(number);
std::cout << number_as_string << std::endl;
return 0;
}</code>使用 stringstream:
立即学习“C++免费学习笔记(深入)”;
使用 std::stringstream 类将 int 转换为 string。
<code class="cpp">#include <iostream>
#include <sstream>
#include <string>
int main() {
int number = 123;
std::stringstream ss;
ss << number;
std::string number_as_string = ss.str();
std::cout << number_as_string << std::endl;
return 0;
}</code>使用 sprintf:
使用 sprintf() 函数将 int 转换为 string。
<code class="cpp">#include <iostream>
#include <cstdio>
#include <string>
int main() {
int number = 123;
char number_as_string[10];
sprintf(number_as_string, "%d", number);
std::string str_number(number_as_string);
std::cout << str_number << std::endl;
return 0;
}</code>注意:
stoi() 函数可以将 string 转换回 int。std::format() 函数,可以更方便地将 int 格式化为 string。以上就是c++++中int怎么转string的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号