(最简单)方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
char s[]="123 ab 4";
char *p;
char str[10];
int num1, num2;
void main()
{
p=s;
sscanf(p,"%d %s %d",&num1, str, &num2);
printf("num1 = %d\n",num1);
printf("num2 = %d\n",num2);
printf("string is %s\n",str);
}

output:

1
2
3
num1 = 123
num2 = 4
string is ab

(逐个查找)方法二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
char s[]="123 ab 4";
char *p;
int v,n,k;
void main()
{
p=s;
while (1)
{
k=sscanf(p,"%d%n",&v,&n);
printf("k,v,n=%d,%d,%d\n",k,v,n);
if (1==k) //提取到数字
{
p+=n;
}
else if (0==k) //提取到非数字
{
printf("skip char[%c]\n",p[0]);
p++;
}
else //EOF==k
break;
}
printf("End.\n");
}

output:

1
2
3
4
5
6
7
8
9
10
k,v,n=1,123,3
k,v,n=0,123,3
skip char[ ]
k,v,n=0,123,3
skip char[a]
k,v,n=0,123,3
skip char[b]
k,v,n=1,4,2
k,v,n=-1,4,2
End.

(正则表达式:匹配正负号和小数点)方法三:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>  
#include <string>
#include <regex>

using namespace std;

int main()
{
regex pattern("-?[0-9]\\d*\\.[0-9]\\d*");

string str_1 = "v -1234.3/234.5/3.4567 3.4/5.6/7.88 67.8/8.901/7.65";
string::const_iterator start = str_1.begin();
string::const_iterator end = str_1.end();

smatch mat;
while (regex_search(start, end, mat, pattern))
{
string msg(mat[0].first, mat[0].second);
cout << msg << endl;
start = mat[0].second;
}
return 0;
}

output:

1
2
3
4
5
6
7
8
9
-1234.3
234.5
3.4567
3.4
5.6
7.88
67.8
8.901
7.65