C++字符串转化为数字
时间: 2025-03-03 20:41:49 浏览: 95
在C++中,将字符串转化为数字可以通过多种方法实现。以下是一些常用的方法:
1. **使用`stringstream`类**:
- `stringstream`是C++标准库中的一个类,可以用来对字符串进行输入输出操作。它基于字符串的流,可以将字符串转换为其他类型的数据,以及将其他类型的数据转换为字符串。
- 示例代码:
```cpp
#include<iostream>
#include<sstream>
using namespace std;
int main() {
stringstream ss;
string s = "12345";
int num;
ss << s; // 将字符串读入字符串流
ss >> num; // 从字符串流中读取数据转换为整数
cout << typeid(num).name() << " " << num << endl;
return 0;
}
```
2. **使用`stoi`函数**:
- `stoi`函数是C++11引入的,用于将字符串转换为整数。它适用于C++字符串和C风格的字符串。
- 示例代码:
```cpp
#include<iostream>
#include<string>
using namespace std;
int main() {
string s = "12345";
int a = stoi(s);
cout << "int:" << a << endl;
return 0;
}
```
3. **使用`atoi`函数**:
- `atoi`函数是C语言中的一个函数,主要用于将字符串转换为整数。它适用于字符数组或以null结尾的字符串。
- 示例代码:
```cpp
#include<iostream>
#include<cstring>
using namespace std;
int main() {
char s[] = "12345";
int a = atoi(s);
cout << "int:" << a << endl;
return 0;
}
```
4. **使用`sscanf`函数**:
- `sscanf`函数是一个用来将字符串按照指定格式解析的函数。它接受一个输入字符串和一个格式字符串作为参数,并根据格式字符串的指示将字符串中的数据解析为对应的变量中。
- 示例代码:
```cpp
#include<iostream>
#include<cstring>
using namespace std;
int main() {
char s[] = "12345";
int a;
sscanf(s, "%d", &a);
cout << "int:" << a << endl;
return 0;
}
```
综上所述,C++提供了多种方法来实现字符串到数字的转换,开发者可以根据具体需求选择合适的方法。
阅读全文
相关推荐



















