頭文件:#include <stdio.h>
sscanf()函數用於從字符串中讀取指定格式的數據,其原型如下:
int sscanf (char *str, char * format [, argument, ...]);
【參數】參數str為要讀取數據的字符串;format為用戶指定的格式;argument為變量,用來保存讀取到的數據。
【返回值】成功則返回參數數目,失敗則返回-1,錯誤原因存於errno 中。
sscanf()會將參數str 的字符串根據參數format(格式化字符串)來轉換並格式化數據(格式化字符串請參考scanf()), 轉換后的結果存於對應的變量中。
sscanf()與scanf()類似,都是用於輸入的,只是scanf()以鍵盤(stdin)為輸入源,sscanf()以固定字符串為輸入源。
【實例】從指定的字符串中讀取整數和小寫字母
#include <stdio.h> int main() { char str[] = "123568qwerSDDAE"; char lowercase[10]; int num; sscanf(str, "%d %[a-z]", &num, lowercase); printf("The number is: %d\n", num); printf("THe lowercase is: %s\n", lowercase); //===================== 分割字符串 ========================== int a, b, c; sscanf("2006:03:18", "%d:%d:%d", &a, &b, &c); printf("a: %d, b: %d, c: %d\n", a, b, c); char time1[20]; char time2[20]; sscanf("2006:03:18 - 2006:04:18", "%s - %s", time1, time2); printf("time1: %s, time2: %s\n", time1, time2); return 0; }
運行結果:
The number is: 123568 THe lowercase is: qwer a: 2006, b: 3, c: 18 time1: 2006:03:18, time2: 2006:04:18
可以看到format參數有些類似正則表達式(當然沒有正則表達式強大,復雜字符串建議使用正則表達式處理),支持集合操作,例如:
%[a-z] 表示匹配a到z中任意字符,貪婪性(盡可能多的匹配)
%[aB'] 匹配a、B、'中一員,貪婪性
%[^a] 匹配非a的任意字符,貪婪性
另外,format不僅可以用空格界定字符串,還可以用其他字符界定,可以實現簡單的字符串分割(更加靈活的字符串分割請使用strtok() 函數)。比如上面的code:
int a, b, c; sscanf("2006:03:18", "%d:%d:%d", &a, &b, &c); printf("a: %d, b: %d, c: %d\n", a, b, c); char time1[20]; char time2[20]; sscanf("2006:03:18 - 2006:04:18", "%s - %s", time1, time2); printf("time1: %s, time2: %s\n", time1, time2);
See: C語言sscanf()函數:從字符串中讀取指定格式的數據