新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c++中int转string的有哪些方法,c++ int转为string类型

发布时间:2023-10-14 00:23:18

c++中int转string的有哪些方法

在C++中,可使用以下几种方法将int转换为string:

  1. 使用std::to_string函数:std::to_string是C++11标准库中的一个函数,它可以将整数转换为对应的字符串。示例代码以下:
int num = 123;
std::string str = std::to_string(num);
  1. 使用std::stringstream类:std::stringstream是C++标准库中的一个类,它可以将各种类型的数据转换为字符串。示例代码以下:
#include 
int num = 123;
std::stringstream ss;
ss << num;
std::string str = ss.str();
  1. 使用std::sprintf函数:std::sprintf是C标准库中的一个函数,可以将格式化的文本输出到一个字符数组中。可以利用这个函数将整数转换为字符串。示例代码以下:
#include 
int num = 123;
char buf[10];
std::sprintf(buf, "%d", num);
std::string str(buf);

以上是三种经常使用的将int转换为string的方法,根据实际情况选择合适的方法便可。