Can I fly high in the Sky?

Never say never.

导航

c++中从一段字符串中提取数字

Posted on 2015-05-06 20:16  lsr_flying  阅读(16091)  评论(1编辑  收藏  举报

采用标准输入输出:

 

输入:12&3 34*133^3131   13031*

输出:12 3 34 133 3131 13031

 

思路,先将整个输入存进一个字符串,再解析字符串,这样运行速度会快些。

 1 int GetNum(const char* str,int* num)   //输入:str---字符串指针,num---要保存数字的数组指针      返回:数字个数
 2 {
 3     int len=strlen(str);
 4     int index=0;
 5     int t;
 6     for(int i=0;i<len;i++)
 7     {
 8         while(!(str[i]>'0'&&str[i]<'9'))
 9         {
10             i++;
11         }
12         while(str[i]>='0'&&str[i]<'9')
13         {
14           t=str[i]-'0';
15           num[index]=num[index]*10+t;
16           i++;
17         }
18         index++;
19     }
20     return index;
21 }