字符串中的数字(字符串、循环)

问题描述】
输入一个字符串,内有数字和非数字字符。
如:a123x456 17960?302tab5876,将其中连续的数字作为一个整数,依次存放到一个数组a中。
例如,123存放在a[0],456存放在a[1]…
统计共有多少个整数,并输出这些整数。
输入串中含有空格,可以用cin.getline(str,30,’ ’)接收串,其中str是char str[30]。

【样例输入】
a123x456 17960?302tab5876

【样例输出】
5
123 456 17960 302 5876

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    int i = 0, index = 0, Count = 0;
    char str[30];
    int a[30];
    cin.getline(str,30,'
');

    while( i<(int)strlen(str) )//遍历str中的每一个元素
    {
        if( str[i]>='0' && str[i]<='9' )//如果下标为i的元素是数字字符
        {
            int j;
            Count++;
            int temp = str[i]-'0';//用一个局部变量存储这个数值
            for( j=i+1; str[j]>='0' && str[j]<='9'; ++j )//如果字符是数字,就继续循环,不是就跳出
                temp = 10*temp + str[j] - '0';//用算法把字符串数字转化成数值
            a[index] = temp;//a数组的下标必须要开辟index下标,不能用i来代替,因为i是一只在变的,不能实现一个一个增加
            index++;
            i = j-1;//把下标i只到下一个要遍历的字符的前一个
        }
        i++;//指到下一个要遍历的字符
    }

    cout << Count << endl;
    cout << a[0];
    for( int k=1; k<Count; ++k )
        cout << " " << a[k];
    cout << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/yuzilan/p/10626128.html