c++ string转int数组
时间: 2023-10-24 13:25:31 浏览: 163
可以使用 `std::stoi()` 函数将字符串转换为整数,然后将整数存入数组中。以下是示例代码:
```cpp
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string str = "12345";
std::vector<int> arr;
for (char c : str) {
int num = std::stoi(std::string(1, c));
arr.push_back(num);
}
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
1 2 3 4 5
```
在代码中,我们首先定义一个字符串 `str` 和一个整数数组 `arr`,然后使用 `for` 循环遍历字符串中的每个字符。在循环中,我们使用 `std::stoi()` 函数将字符转换为整数,并使用 `std::string(1, c)` 构造一个只包含当前字符的字符串作为 `std::stoi()` 函数的参数。最后将转换后的整数存入数组中。最后再使用一个 `for` 循环输出整数数组中的所有元素。
相关问题
C++string转换为int数组
以下是将C字符串转换为int数组的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char str[] = "1 2 3 4 5";
int arr[5];
char *ptr = strtok(str, " ");
int i = 0;
while (ptr != NULL) {
arr[i++] = atoi(ptr);
ptr = strtok(NULL, " ");
}
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
在这个示例中,我们首先声明了一个包含5个整数的int数组。然后,我们使用strtok函数将C字符串分割成子字符串,并将它们转换为整数使用atoi函数。最后,我们遍历整个数组并打印每个元素。
C++ string 转char数组
可以使用`c_str()`函数将C++中的string对象转换为char数组。
例如:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
const char* charArr = str.c_str();
cout << charArr << endl;
return 0;
}
```
输出:
```
hello world
```
注意,`c_str()`函数返回的是一个指向内部字符数组的指针,因此在使用时需要注意该指针是否有效(例如,string对象被销毁后,指针就无效了)。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)