scanf
, _scanf_l
, wscanf
, _wscanf_l
從標準輸入資料流讀取格式化資料。 這些函式有更安全的版本可供使用;請參閱 、、 wscanf_s
_scanf_s_l
、 _wscanf_s_l
。 scanf_s
注意
在 Visual Studio 2015 中,函 printf
式的 和 scanf
系列已宣告為 inline
,並移至 <stdio.h>
和 <conio.h>
標頭。 如果您要移轉較舊的程式碼,您可能會看到連結器錯誤LNK2019與這些函式連線。 如需詳細資訊,請參閱 Visual C++ 變更歷程記錄 2003 - 2015 。
語法
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
。
如需這些錯誤碼和其他錯誤碼的相關資訊,請參閱 errno
、 _doserrno
_sys_errlist
和 _sys_nerr
。
備註
scanf
函式會從標準輸入資料流 stdin
讀取資料,並將資料寫入由 argument
指定的位置。 每個 argument
必須是 format
中對應至型別指定名稱的型別變數指標。 如果在重疊的字串之間執行複製,則行為是未定義的。
重要
使用 scanf
讀取字串時,請一律指定 %s
格式的寬度 (例如,%32s
,而非 %s
);否則,格式不正確的輸入很容易造成緩衝區滿溢。 或者,請考慮使用 scanf_s
、 _scanf_s_l
、 wscanf_s
_wscanf_s_l
或 。 fgets
wscanf
是寬字元版本的 scanf
; format
的 wscanf
引數是寬字元字串。 如果資料流在 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 平臺 (UWP) 應用程式中不支援主控台。 與主控台、 stdin
、 stdout
和 stderr
相關聯的標準資料流程控制碼必須先重新導向,C 執行時間函式才能在 UWP 應用程式中使用這些控制碼。 如需相容性詳細資訊,請參閱相容性。
範例
// 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);
}
71 98.6 h z Byte characters
36 92.3 y n Wide characters
The number of fields input is 6
The contents are: 71 98.599998 h z Byte characters
The number of fields input is 6
The contents are: 36 92.300003 y n Wide characters
另請參閱
數學和浮點支援
資料流 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
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應