用c++写,新string a = “5,0,1,2,10,0,51”,提取出7个数字
时间: 2024-06-10 11:06:35 浏览: 6
好的,我可以帮您解决这个问题。
您可以使用以下代码来提取这7个数字:
```
#include <stdio.h>
int main() {
char *a = "5,0,1,2,10,0,51";
int nums[7];
int count = 0;
for (int i = 0; i < strlen(a); i++) {
if (a[i] >= '0' && a[i] <= '9') {
nums[count] = a[i] - '0';
count++;
}
}
printf("提取出的数字为: ");
for (int i = 0; i < count; i++) {
printf("%d ", nums[i]);
}
return 0;
}
```
运行结果将会输出:
```
提取出的数字为: 5 0 1 2 1 0 5 1
```
希望这个代码能够帮助您!
相关问题
用c++写,string a = “5,0,1,2,10,0,51”,用char* b 指向a
的地址,把字符串b拆分成数字,分别存储到一个数组c中?
这是一个计算问题,我可以回答。以下是用C语言写的程序,可以实现将字符串b中的数字拆分并存储到数组c中:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* b = "5,0,1,2,10,0,51";
char* p = strtok(b, ",");
int c[7], i = 0;
while(p != NULL) {
c[i++] = atoi(p);
p = strtok(NULL, ",");
}
for(i = 0; i < 7; i++) {
printf("%d ", c[i]);
}
return 0;
}
```
以上是将字符串b中的数字拆分并存储到数组c中的C语言程序。
用c++写,新建字符串 a = “5,0,1,2,10,0,51”,提取出7个数字
Sure, I can help you with that. Here's the code to extract the 7 numbers from the given string:
```c
#include <stdio.h>
#include <string.h>
int main() {
char a[] = "5,0,1,2,10,0,51"; // the given string
int nums[7]; // array to store the extracted numbers
char *token; // pointer to hold each token
int i = 0;
token = strtok(a, ",");
while(token != NULL) {
nums[i++] = atoi(token); // convert token to integer and store in array
token = strtok(NULL, ",");
}
// print the extracted numbers
for(int j = 0; j < 7; j++) {
printf("%d ", nums[j]);
}
return 0;
}
```
Output:
```
5 0 1 2 10 0 51
```
相关推荐
![](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)