共用方式為


scanf、 _scanf_l、 wscanf、 _wscanf_l

讀取從標準輸入資料流的格式化資料。 更安全版本這些函式可用的;請參閱 scanf_s、 _scanf_s_l、 wscanf_s、 _wscanf_s_l

int scanf(
   const char *format [,
   argument]... 
);
int _scanf_l(
   const char *format,
   locale_t locale [,
   argument]... 
);
int wscanf(
   const wchar_t *format [,
   argument]... 
);
int _wscanf_l(
   const wchar_t *format,
   locale_t locale [,
   argument]... 
);

參數

  • format
    格式控制字串。

  • argument
    選擇性參數。

  • locale
    使用的地區設定。

傳回值

傳回欄位轉換成功的和指定數字;傳回值不包括讀取,但未指定的欄位。 傳回值 0 表示欄位未指定。

如果 format 是 NULL 指標,無效的參數叫用處理常式,如 參數驗證中所述。 如果執行允許繼續執行,這些函式傳回 EOF 並將 errno 設為 EINVAL。

如需這些屬性和其他錯誤碼的詳細資訊,請參閱 _doserrno、errno、_sys_errlist 和 _sys_nerr

備註

scanf 函式會從標準輸入資料流 stdin 的資料並將資料寫入 argument指定的位置。 每個 argument 必須是指標對應至 format的型別規範型別的變數。 如果複製發生在重疊的字串之間,行為是未定義。

安全性注意事項安全性提示

當讀取與 scanf的字串時,為 %s 格式永遠指定寬度 (例如,而不是 "%s"中的 "%32s" );否則,格式化輸入容易不適當地造成緩衝區滿溢。此外,使用 scanf_s、 _scanf_s_l、 wscanf_s、 _wscanf_s_lfgets,請考慮。

wscanf 是 scanf 的寬字元版本。傳遞給 wscanf 的參數 format 的寬字元字串。 如果串流是以 ANSI 模式開啟,則 wscanf 和 scanf 的行為相同。 scanf 目前不支援從 UNICODE 資料流的輸入。

這些函式的以 _l 後綴版本相同,但使用傳遞的地區設定參數而非目前執行緒的地區設定。

泛用文字常式對應

TCHAR.H 常式

未定義 _UNICODE & _MBCS

已定義 _MBCS

已定義 _UNICODE

_tscanf

scanf

scanf

wscanf

_tscanf_l

_scanf_l

_scanf_l

_wscanf_l

如需詳細資訊,請參閱 格式規格欄位— scanf 函式和 wscanf 函式

需求

程序

必要的標頭檔

scanf, _scanf_l

<stdio.h>

wscanf, _wscanf_l

<stdio.h> 或 <wchar.h>

主控台 Windows 市集 應用程式不支援。 標準資料流控制代碼與主控台, stdin, stdout和 stderr,在這種情況下, C 執行階段函式在 Windows 市集 應用程式之前,可以使用它們必須重新導向。 如需其他相容性資訊,請參閱入門介紹中的 相容性 (Compatibility)

範例

// crt_scanf.c
// compile with: /W3
 /* This program uses the scanf and wscanf functions
  * to read formatted input.
  */

#include <stdio.h>

int main( void )
{
   int   i, result;
   float fp;
   char  c, s[81];
   wchar_t wc, ws[81];
   result = scanf( "%d %f %c %C %80s %80S", &i, &fp, &c, &wc, s, ws ); // C4996
   // Note: scanf and wscanf are deprecated; consider using scanf_s and wscanf_s
   printf( "The number of fields input is %d\n", result );
   printf( "The contents are: %d %f %c %C %s %S\n", i, fp, c, wc, s, ws);
   result = wscanf( L"%d %f %hc %lc %80S %80ls", &i, &fp, &c, &wc, s, ws ); // C4996
   wprintf( L"The number of fields input is %d\n", result );
   wprintf( L"The contents are: %d %f %C %c %hs %s\n", i, fp, c, wc, s, ws);
}
  

.NET Framework 對等用法

請參閱

參考

浮點支援

資料流 I/O

地區設定

fscanf、 _fscanf_l、 fwscanf、 _fwscanf_l

printf、 _printf_l、 wprintf、 _wprintf_l

sprintf、 _sprintf_l、 swprintf、 _swprintf_l、 __swprintf_l

sscanf、 _sscanf_l、 swscanf、 _swscanf_l