C++string转换为jnt
时间: 2024-06-15 12:08:39 浏览: 15
C++中的string转换为int可以使用以下几种方法:
1. 使用stoi函数:可以使用stoi函数将string转换为int。示例代码如下:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "123";
int num = std::stoi(str);
std::cout << num << std::endl;
return 0;
}
```
2. 使用stringstream类:可以使用stringstream类将string转换为int。示例代码如下:
```cpp
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string str = "123";
std::stringstream ss(str);
int num;
ss >> num;
std::cout << num << std::endl;
return 0;
}
```
3. 使用atoi函数:可以使用atoi函数将string转换为int。示例代码如下:
```cpp
#include <iostream>
#include <cstdlib>
int main() {
std::string str = "123";
int num = std::atoi(str.c_str());
std::cout << num << std::endl;
return 0;
}
```
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)