轉自原文 scanf,fscanf,sscanf的區別----整理
scanf 從控制台輸入
fscanf 從文件輸入
sscanf 從指定字符串輸入
1、例:使用scanf函數輸入數據。
3、大家都知道sscanf是一個很好用的函數,利用它可以從字符串中取出整數、浮點數和字符串等等。它的使用方法簡單,特別對於整數和浮點數來說。但新手可能並不知道處理字符串時的一些高級用法,這里做個簡要說明吧。
1. 常見用法。
char str[512] = {0};
sscanf("123456 ", "%s", str);
printf("str=%s\n", str);
2. 取指定長度的字符串。如在下例中,取最大長度為4字節的字符串。
sscanf("123456 ", "%4s", str);
printf("str=%s\n", str);//str的值為1234
3. 取到指定字符為止的字符串。如在下例中,取遇到空格為止字符串。
sscanf("123456 abcdedf", "%[^ ]", str);//注意^后面有一空格
printf("str=%s\n", str);
4. 取僅包含指定字符集的字符串。如在下例中,取僅包含1到9和小寫字母的字符串。
sscanf("123456abcdedfBCDEF", "%[1-9a-z]", str);
printf("str=%s\n", str);
5. 取到指定字符集為止的字符串。如在下例中,取遇到大寫字母為止的字符串。
sscanf("123456abcdedfBCDEF", "%[^A-Z]", str);
printf("str=%s\n", str);
源代碼一如下:
#include <stdio.h> #include <stdlib.h> char *tokenstring = "12:34:56-7890"; char a1[3], a2[3], a3[3]; int i1, i2; void main(void) { sscanf(tokenstring, "%2s:%2s:%2s-%2d%2d", a1, a2, a3, &i1, &i2); printf("%s\n%s\n%s\n%d\n%d\n\n", a1, a2, a3, i1, i2); getch(); }
源代碼二如下:
#include <stdio.h> #include <stdlib.h> char *tokenstring = "12:34:56-7890"; char a1[3], a2[3], a3[3],a; int i1, i2; void main(void) { sscanf(tokenstring, "%2s%1s%2s%1s%2s%1s%2d%2d", a1, &a, a2, &a3, a3, &a, &i1, &i2); printf("%s\n%s\n%s\n%d\n%d\n\n", a1, a2, a3, i1, i2); getch(); }
結果同上
源代碼三如下:
#include <stdio.h> #include <stdlib.h> char *tokenstring = "12:34:56-7890"; char a1[3], a2[3], a3[3], a4[3], a5[3]; int i1, i2; void main(void) { char a; sscanf(tokenstring, "%2s%1s%2s%1s%2s%1s%2s%2s", a1, &a, a2, &a3, a3, &a, a4, a5); i1 =atoi(a4); i2 =atoi(a5); printf("%s\n%s\n%s\n%d\n%d\n\n", a1, a2, a3, i1, i2); getch(); }
結果同上
方法四如下(以實例說明,原理相同):
/* The following sample illustrates the use of brackets and the caret (^) with sscanf(). Compile options needed: none */ #include <math.h> #include <stdio.h> #include <stdlib.h> char *tokenstring = "first,25.5,second,15"; int result, i; double fp; char o[10], f[10], s[10], t[10]; void main() { result = sscanf(tokenstring, "%[^','],%[^','],%[^','],%s", o, s, t, f); fp = atof(s); i = atoi(f); printf("%s\n %lf\n %s\n %d\n", o, fp, t, i); }