C++练习:统计字符串中连续的数字
题目要求
编写程序:
主函数中,输入一行字符,内有数字和非数字字符,例如A123x45 1790#¥576,编写函数int con(char * ,int * )实现将其中连续的数字作为一个整数,依次存放到一数组a中,例如123放在a[0],45放在a[1]……。并统计共有多少个数字,返回数字个数,在主函数中输出这些数字。
(提示:数组a在主函数中定义,数组长度可以定义大一些,比如40个,但输出结果一定是实际个数)
PS:我用的是visual studio 2019,所以不用加一些头文件
代码部分
#include<iostream>
using namespace std;
int con(char* strp, int* nump)
{
int count = 0, n;
while (*strp)
{
n = 0;
while (*strp >= '0' && *strp <= '9')
{
n = n * 10 + *strp - '0';
if (*(strp + 1) < '0' || *(strp + 1) > '9')
{
*nump++ = n; count++; break;
}
strp++;
}
strp++;
}
return count;
}
int main()
{
/*编写程序:
主函数中,输入一行字符,内有数字和非数字字符,例如A123x45 1790#¥576,编写函数int con(char * ,int * )实现将其中连续的数字作为一个整数,依次存放到一数组a中,例如123放在a[0],45放在a[1]……。并统计共有多少个数字,返回数字个数,在主函数中输出这些数字。
(提示:数组a在主函数中定义,数组长度可以定义大一些,比如40个,但输出结果一定是实际个数)*/
char str[81];
int num[40], count;
cin.getline(str, 81);
count = con(str, num);
cout << "数字个数为:" << count << endl << "数字为:";
for (int i = 0; i < count; i++)
{
cout << num[i] << '\t';
}
cout << endl;
return 0;
}
结果