c++怎么把int转string
时间: 2024-06-13 13:07:38 浏览: 9
以下是两种C++将int转换为string的方法:
1.使用to_string()函数
```c++
int i = 10;
string str = to_string(i);
cout << "int_str: " << str << endl; // 输出:int_str: 10
```
2.使用stringstream类
```c++
#include <sstream>
int i = 10;
stringstream ss;
ss << i;
string str = ss.str();
cout << "int_str: " << str << endl; // 输出:int_str: 10
```
相关问题
c++11 int转string
两种将int类型转换为string类型的方法如下:
1. 使用C++11标准引入的std::to_string()函数。
```c++
#include <iostream>
#include <string>
int main() {
int num = 12345;
std::string str = std::to_string(num);
std::cout << str << std::endl; // 输出:12345
return 0;
}
```
2. 使用stringstream类。
```c++
#include <iostream>
#include <sstream>
int main() {
int num = 12345;
std::stringstream ss;
ss << num;
std::string str = ss.str();
std::cout << str << std::endl; // 输出:12345
return 0;
}
```
c++ 11 int转string
在C++11中,可以使用std::to_string函数将int类型转换为string类型。例如:
```c++
int num = 123;
std::string str = std::to_string(num);
```
这将把整数123转换为字符串"123"。需要注意的是,std::to_string函数只能用于内置类型,如果要将自定义类型转换为字符串,需要重载<<运算符或者使用boost库中的lexical_cast函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)