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