如何将字符串转成数字
时间: 2024-06-16 20:08:06 浏览: 12
将字符串转换成数字可以使用C++中的库函数 `atoi()` 或者 `std::stoi()`。
1. 使用 `atoi()` 函数
`atoi()` 函数可以将字符串转换为整数,其函数原型如下:
```c++
int atoi(const char* str);
```
其中,`str` 是要转换的字符串。
示例代码如下:
```c++
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char str[] = "123";
int num = atoi(str);
cout << "转换后的数字为:" << num << endl;
return 0;
}
```
2. 使用 `std::stoi()` 函数
`std::stoi()` 函数可以将字符串转换为整数,其函数原型如下:
```c++
int stoi(const string& str, size_t* pos = 0, int base = 10);
```
其中,`str` 是要转换的字符串,`pos` 是可选参数,指向第一个未被转换的字符的指针;`base` 是可选参数,表示要转换的进制,默认是10进制。
示例代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "123";
int num = stoi(str);
cout << "转换后的数字为:" << num << endl;
return 0;
}
```
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)