c++怎么将string数组转变为int数组
时间: 2024-02-13 12:07:28 浏览: 20
要将一个string数组转换为int数组,可以使用以下代码:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string str_arr[] = {"12", "345", "6789"};
int int_arr[3];
vector<int> int_vec;
// 方法1:使用stoi函数
for(int i = 0; i < 3; i++) {
int_arr[i] = stoi(str_arr[i]);
cout << int_arr[i] << " ";
}
cout << endl;
// 方法2:使用stringstream
for(int i = 0; i < 3; i++) {
stringstream ss(str_arr[i]);
int num;
ss >> num;
int_vec.push_back(num);
}
for(int i = 0; i < int_vec.size(); i++) {
cout << int_vec[i] << " ";
}
cout << endl;
return 0;
}
```
在上面的代码中,我们使用了两种方法将string数组转换为int数组。第一种方法是使用 `stoi` 函数,它可以将一个字符串转换为对应的整数。第二种方法是使用 `stringstream`,它可以将一个字符串转换为流,然后我们从流中读取整数。