詳解C語言sscanf()函數、vsscanf()函數、vscanf()函數_C 語言

來源:互聯網
上載者:User

C語言sscanf()函數:從字串中讀取指定格式的資料
標頭檔:

#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(void){  char str[100] ="123568qwerSDDAE";  char lowercase[100];  int num;  sscanf(str,"%d %[a-z]", &num, lowercase);  printf("The number is: %d.\n", num);  printf("The lowercase is: %s.", lowercase);  return 0;}

輸出結果:

The number is: 123568.The lowercase is: qwer.

可以看到format參數有些類似Regex(當然沒有Regex強大,複雜字串建議使用Regex處理),支援集合操作,例如:

  •     %[a-z] 表示匹配a到z中任一字元,貪婪性(儘可能多的匹配)
  •     %[aB'] 匹配a、B、'中一員,貪婪性
  •     %[^a] 匹配非a的任一字元,貪婪性

另外,format不僅可以用空格界定字串,還可以用其他字元界定,可以實現簡單的字串分割(更加靈活的字串分割請使用strtok())。例如:

  sscanf("2006:03:18", "%d:%d:%d", a, b, c);  sscanf("2006:03:18 - 2006:04:18", "%s - %s", sztime1, sztime2);

C語言vsscanf()函數:字串輸入函數
標頭檔:

 #include <stdio.h>

定義函數:

int vsscanf(const char * str, const char * format, va_list ap);

函數說明:vsscanf()會將參數str 的字串根據參數format 字串來轉換並格式化資料. 格式轉換形式請參考附錄C 或vprintf()範例。

傳回值:成功則返回參數數目, 失敗則返回-1, 錯誤原因存於errno 中.

C語言vscanf()函數:字串格式化輸入函數
標頭檔:

#include <stdio.h>  #include <stdarg.h>

定義函數:

int vscanf(const char * format, va_list ap);

函數說明:vscanf()會將輸入的資料根據參數format 字串來轉換並格式化資料. 格式轉換形式請參考scanf(). 轉換後的結果存於對應的參數內. va_list 用法請參考附錄C 或vprintf()範例.
傳回值成功則返回參數數目, 失敗則返回-1, 錯誤原因存於errno 中。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.