名稱:
sscanf() 從一個字符串中,讀入指定格式的數據。
函數定義:
int sscanf( const char *buffer, const char *format [, argument ] ... );
參數:
buffer
Stored data.
format
Format-control string.
argument
Optional arguments.
Return Values
Each of these functions returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error
or if the end of the string is reached before the first conversion.
其中的format可以是一個或多個 {%[*] [width] [{h | l | I64 | L}]type | ' ' | '/t' | '/n' | 非%符號}
注:
1、 * 亦可用於格式中, (即 %*d 和 %*s) 加了星號 (*) 表示跳過此數據不讀入. (也就是不把此數據讀入參數中)
2、{a|b|c}表示a,b,c中選一,[d],表示可以有d也可以沒有d。
3、width表示讀取寬度。
4、{h | l | I64 | L}:參數的size,通常h表示單字節size,I表示2字節 size,L表示4字節size(double例外),l64表示8字節size。
5、type :這就很多了,就是%s,%d之類。
6、特別的:%*[width] [{h | l | I64 | L}]type 表示滿足該條件的被過濾掉,不會向目標參數中寫入值
支持集合操作:
%[a-z] 表示匹配a到z中任意字符,貪婪性(儘可能多的匹配)
%[aB'] 匹配a、B、'中一員,貪婪性
%[^a] 匹配非a的任意字符,貪婪性
例子:
1、常見用法。提取前n個字符
char buff[1024] = {0, };
sscanf("1234567890", "%3s", buff);
結果爲:123
2、取到指定字符爲止的字符串。在下例中,取遇到'@'爲止的字符串
char buff[1024] = {0, };
sscanf("[email protected]", "%[^@]", buff);
結果爲:shaozg1101
3、取到指定字符集的字符串。在下例中,取僅包含小寫字母的串
char buff[1024] = {0, };
sscanf("abcde12345ABCDE", "%[a-z]", buff);
結果爲:abcde
4、給定一個字符串,提取中間的部分。在下例中,取google
char buff[1024] = {0, };
sscanf("http://www.google.com.hk", "%*[^.].%[^.]", buff);
結果爲:google
5、提取表名。在下例中,提取table
char buff[1024] = {0, };
sscanf("user.table", "%*[^.].%s", buff);
結果爲:table