sscanf
, _sscanf_l
, swscanf
, _swscanf_l
從字串讀取格式化資料。 這些函式有更安全的版本可供使用;請參閱 、、 swscanf_s
_sscanf_s_l
、 _swscanf_s_l
。 sscanf_s
語法
int sscanf(
const char *buffer,
const char *format [,
argument ] ...
);
int _sscanf_l(
const char *buffer,
const char *format,
_locale_t locale [,
argument ] ...
);
int swscanf(
const wchar_t *buffer,
const wchar_t *format [,
argument ] ...
);
int _swscanf_l(
const wchar_t *buffer,
const wchar_t *format,
_locale_t locale [,
argument ] ...
);
參數
buffer
已儲存資料
format
格式控制字串。 如需詳細資訊,請參閱 格式規格語法 。
argument
選擇性引數
locale
要使用的地區設定
傳回值
每個函式都會傳回成功轉換和指派的欄位數目;傳回值不包含已讀取但未指派的欄位。 傳回值 0 表示未指派任何欄位。 傳回值是 EOF
,其表示發生錯誤或在進行第一次轉換之前就到達字串結尾。
如果 buffer
或 format
為 NULL
指標,則會叫用不正確參數處理常式,如參數驗證 中所述 。 如果允許繼續執行,這些函式會傳回 -1,並將 errno
設為 EINVAL
。
如需這些錯誤碼和其他錯誤碼的相關資訊,請參閱 errno
、 _doserrno
_sys_errlist
和 _sys_nerr
。
備註
sscanf
函式會將 buffer
中的資料讀入每個 argument
所指定的位置。 每個 argument
都必須是變數的指標,而變數的類型對應至 format
中的類型指定名稱。 format
引數會控制輸入欄位的解譯,而且形式和功能與 scanf
函式的 format
引數相同。 如果在重疊的字串之間執行複製,則行為是未定義的。
如需 scanf 類型欄位字元的相關資訊,請參閱 scanf
類型欄位字元 。 如需 scanf 格式規格欄位的相關資訊,請參閱 格式規格欄位 。
重要
使用 sscanf
讀取字串時,一律指定 %s
格式的寬度(例如 「 %32s
」 而不是 「 %s
」), 否則,格式不正確的輸入很容易造成緩衝區滿溢。
swscanf
是 sscanf
的寬字元版本; swscanf
的引數是寬字元字串。 sscanf
不會處理多位元組十六進位字元。 swscanf
不會處理 Unicode 全形十六進位或「相容性區域」字元。 否則 swscanf
和 sscanf
的行為相同。
這些有 _l
尾碼的函式版本是一樣的,不同之處在於會使用傳入的地區設定,而不使用目前的執行緒地區設定。
泛型文字常式對應
TCHAR.H 常規 |
_UNICODE 和 _MBCS 未定義 |
_MBCS 定義 |
_UNICODE 定義 |
---|---|---|---|
_stscanf |
sscanf |
sscanf |
swscanf |
_stscanf_l |
_sscanf_l |
_sscanf_l |
_swscanf_l |
需求
常式 | 必要的標頭 |
---|---|
sscanf , _sscanf_l |
<stdio.h> |
swscanf , _swscanf_l |
<stdio.h> 或 <wchar.h> |
如需相容性詳細資訊,請參閱相容性。
範例
// crt_sscanf.c
// compile with: /W3
// This program uses sscanf to read data items
// from a string named tokenstring, then displays them.
#include <stdio.h>
int main( void )
{
char tokenstring[] = "15 12 14...";
char s[81];
char c;
int i;
float fp;
// Input various data from tokenstring:
// max 80 character string:
sscanf( tokenstring, "%80s", s ); // C4996
sscanf( tokenstring, "%c", &c ); // C4996
sscanf( tokenstring, "%d", &i ); // C4996
sscanf( tokenstring, "%f", &fp ); // C4996
// Note: sscanf is deprecated; consider using sscanf_s instead
// Output the data read
printf( "String = %s\n", s );
printf( "Character = %c\n", c );
printf( "Integer: = %d\n", i );
printf( "Real: = %f\n", fp );
}
String = 15
Character = 1
Integer: = 15
Real: = 15.000000
另請參閱
資料流 I/O
fscanf
, _fscanf_l
, fwscanf
, _fwscanf_l
scanf
, _scanf_l
, wscanf
, _wscanf_l
sprintf
, _sprintf_l
, swprintf
, _swprintf_l
, __swprintf_l
snprintf
, _snprintf
, _snprintf_l
, _snwprintf
, _snwprintf_l
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應