int 转std::string
时间: 2023-12-13 15:32:03 浏览: 34
以下是两种将int类型转换为std::string类型的方法:
1. 使用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;
}
```
相关问题
int 转std::string
以下是两种将int类型转换为std::string类型的方法:
1. 使用std::to_string()函数
```cpp
#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类
```cpp
#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++ int转std::string
你可以使用 C++ 的标准库中的 std::to_string() 函数将整数类型转换为 std::string 类型。例如,下面的代码将整数变量 num 转换为字符串:
```c++
int num = 123;
std::string str = std::to_string(num);
```
这将把整数 123 转换为字符串 "123"。注意,使用 std::to_string() 转换整数时,结果字符串中不包含符号 '+' 或 '-'。如果需要包含符号,则需要手动添加。