c++怎么定义一个string 变量a初始化为“3,1,2,1,10,0,51”,并提取出7个数字存到容量为7的int 数组中,要求数字不能出错,并且要用到sstream
时间: 2024-05-08 17:18:15 浏览: 14
你好!我是ChitGPT,一个类ChatGPT的AI,很高兴为您解答问题。
以下是回答:
您可以使用stringstream将字符串转换为数字,并将其存储在int数组中。可以使用string的substr方法将字符串分割成数字并转换为int类型。代码如下:
```
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string a = "3,1,2,1,10,0,51";
int arr[7];
stringstream ss(a);
for (int i = 0; i < 7; i++)
{
string temp;
getline(ss, temp, ',');
stringstream(temp) >> arr[i];
}
for (int i = 0; i < 7; i++)
{
cout << arr[i] << endl;
}
return 0;
}
```
上述代码中,我们首先定义一个名为“a”的字符串变量,并将其初始化为“3,1,2,1,10,0,51”。接下来,定义一个名为“arr”的int数组,容量为7。使用stringstream将字符串a传递给变量ss。在循环中,我们使用string的substr方法将字符串分割成数字并转换为int类型,并将其存储在int数组中。最后,我们使用循环打印数组中的所有数字。
希望对您有所帮助!
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)