string 转换方法
时间: 2023-09-26 15:15:23 浏览: 45
string 转换方法有很多种,可以根据具体需求选择合适的方法。以下是几种常用的转换方法:
1. 使用 stoi() 函数将字符串转换为整数:
```cpp
#include <string>
#include <iostream>
int main() {
std::string str = "12345";
int num = std::stoi(str);
std::cout << num << std::endl; // 输出 12345
return 0;
}
```
2. 使用 stof() 函数将字符串转换为浮点数:
```cpp
#include <string>
#include <iostream>
int main() {
std::string str = "3.14";
float num = std::stof(str);
std::cout << num << std::endl; // 输出 3.14
return 0;
}
```
3. 使用 to_string() 函数将整数或浮点数转换为字符串:
```cpp
#include <string>
#include <iostream>
int main() {
int num1 = 12345;
std::string str1 = std::to_string(num1);
std::cout << str1 << std::endl; // 输出 "12345"
float num2 = 3.14;
std::string str2 = std::to_string(num2);
std::cout << str2 << std::endl; // 输出 "3.140000"
return 0;
}
```
以上是一些常用的字符串转换方法,根据具体需求选择适合的方法即可。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)