87 lines
2.5 KiB
C
87 lines
2.5 KiB
C
/*
|
||
Program: sscanf.c
|
||
Function: 展示sscanf()與qsort()的用法
|
||
Note: 編修自陳鍾誠教授的網站 http://ccckmit.wikidot.com/cp:sscanf
|
||
*/
|
||
|
||
#include <stdio.h>
|
||
|
||
int ascend(const void *a, const void *b); //配合qsort()所用函數,用於比較傳入二元素之大小關係,用於實現遞增或遞減效果
|
||
|
||
int main() {
|
||
char name[20], tel[50], field[20], areaCode[20], code[20];
|
||
int age;
|
||
|
||
sscanf("name:john age:40 tel:082-313530", "%s", name);
|
||
printf("%s\n", name);
|
||
sscanf("name:john age:40 tel:082-313530", "%8s", name);
|
||
printf("%s\n", name);
|
||
sscanf("name:john age:40 tel:082-313530", "%[^:]", name);
|
||
printf("%s\n", name);
|
||
sscanf("name:john age:40 tel:082-313530", "%[^:]:%s", field, name);
|
||
printf("%s %s\n", field, name);
|
||
sscanf("name:john age:40 tel:082-313530", "name:%s age:%d tel:%s", name, &age, tel);
|
||
printf("%s %d %s\n", name, age, tel);
|
||
sscanf("name:john age:40 tel:082-313530", "%*[^:]:%s %*[^:]:%d %*[^:]:%s", name, &age, tel);
|
||
printf("%s %d %s\n", name, age, tel);
|
||
|
||
char protocol[10], site[50], path[50];
|
||
sscanf("http://ccckmit.wikidot.com/cp/list/hello.txt",
|
||
"%[^:]:%*2[/]%[^/]/%[a-zA-Z0-9._/-]",
|
||
protocol, site, path);
|
||
printf("protocol=%s site=%s path=%s\n", protocol, site, path);
|
||
|
||
/*-----------------------------------------------------------------------*/
|
||
|
||
char str[30];
|
||
// char line[] = "Steve Jobs 50 60";
|
||
char line[] = "U. S. Grant 97 88";
|
||
int s1, s2;
|
||
|
||
for (;;) {
|
||
if (sscanf(line,"%[A-Za-z.] %[^\n]",str,line)==0) {
|
||
sscanf(line,"%d %d",&s1,&s2);
|
||
printf("\n最末二數字:s1 = %d; s2 = %d\n",s1,s2);
|
||
break;
|
||
}
|
||
printf("\n讀取出符記:%-10s剩餘內容:%s",str,line);
|
||
}
|
||
|
||
|
||
char fullName[] = "U. S. Grant", tmp[3][24];
|
||
|
||
s1 = sscanf(fullName,"%s %s %s",tmp[0],tmp[1],tmp[2]);
|
||
printf("\n第一種方法找出姓氏:%s",tmp[s1-1]);
|
||
|
||
s1 = sscanf(fullName,"%s %s %s",str,str,str);
|
||
printf("\n第二種方法找出姓氏:%s",str);
|
||
|
||
for (;;) {
|
||
if (sscanf(fullName,"%s %[^\n]",str,fullName) < 2) {
|
||
printf("\n第三種方法找出姓氏:%s",fullName);
|
||
break;
|
||
}
|
||
}
|
||
|
||
/*-----------------------------------------------------------------------*/
|
||
|
||
char bigName[][12] = {"Jobs", "Cruise", "Jane", "Obama", "Tyler", "Grant", "Redford", "Lee"};
|
||
int i, count = sizeof(bigName)/sizeof(bigName[0]),
|
||
size = sizeof(bigName[0]);
|
||
|
||
qsort(bigName,count,size,ascend);
|
||
|
||
printf("\n\n排序後結果如下:\n");
|
||
for (i = 0; i < count; i++)
|
||
printf("%s\n",bigName[i]);
|
||
|
||
return 0;
|
||
}
|
||
|
||
int ascend(const void *a, const void *b) /* 遞增模式 */
|
||
{
|
||
char *x = (char *)a;
|
||
char *y = (char *)b;
|
||
return strcmp(x,y);
|
||
}
|