int NumInString(char s[], int num[]) { … return k; //返回整数的个数 } int main() { char str[]="a123x456&17960?302tab5876"; int num[100] = {0}; int count = 0; count=NumInString(str, num); cout<<"字符串中整数的个数:" << count << endl; for (int i = 0;i < count;i++) cout << num[i] << ","; cout << endl; return 0; }输入一个字符串,内有数字和非数字字符,如:a123x456&17960?302tab5876, 将其中连续的数字作为一个整数,依次存放到一整型数组中。如123放在a[0]中,456放在a[1]中…统计共有多少个整数,并输出这些数。
时间: 2024-01-11 07:03:15 浏览: 63
好的,可以使用循环遍历字符串,判断每个字符是否为数字,如果是就将其累加到整数中,直到遇到非数字字符为止,然后将该整数存入数组中。下面是示例代码:
```c++
#include <iostream>
using namespace std;
int NumInString(char s[], int num[]) {
int i = 0, j = 0, k = 0, n = 0;
while (s[i]) {
if (s[i] >= '0' && s[i] <= '9') {
n = n * 10 + (s[i] - '0');
} else {
if (n > 0) {
num[k++] = n;
n = 0;
}
}
i++;
}
if (n > 0) {
num[k++] = n;
}
return k;
}
int main() {
char str[] = "a123x456&17960?302tab5876";
int num[100] = {0};
int count = 0;
count = NumInString(str, num);
cout << "字符串中整数的个数:" << count << endl;
for (int i = 0; i < count; i++) {
cout << num[i] << ",";
}
cout << endl;
return 0;
}
```
输出结果为:
```
字符串中整数的个数:5
123,456,17960,302,5876,
```
阅读全文