leven同学提到一个简单的功能"12 22 33 22 11"中的数字放到一个数组中,但不知道数字的个数。使用指针一个一个判断是否是数字还是空白,不太爽。而java中的split可以
很爽的处理之。c语言中sscanf似乎是不错的选择,于是使用下面方法,试验成功。
sscanf用法参见[url]http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/[/url]
很爽的处理之。c语言中sscanf似乎是不错的选择,于是使用下面方法,试验成功。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 20
#define MAX_LEN 10
int main(){
char line[] = "12 22 33 22 11";
//the max length of int we used no more than MAX_LEN
char *s = (char *)malloc(MAX_LEN * sizeof(char));
int a[MAX];
char *p = line;
int cur_len;
int i = 0;
while(p && sscanf(p,"%s",s) == 1){
cur_len = strlen(s);
s[cur_len] = '\0';
a[i] = atoi(s);
p += cur_len;
p++;
i++;
}
int j = 0;
for(j = 0; j < i-1; j++){// the i is '\0' in s
printf("%d\t",a[j]);
}
printf("\n");
}
sscanf用法参见[url]http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/[/url]