scanf, _scanf_l, wscanf, _wscanf_l

读取标准输入流中的格式化数据。 这些功能有更安全的版本可用;请参阅 scanf_s_scanf_s_lwscanf_s_wscanf_s_l

注意

在 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 表示没有分配任何字段。

如果 formatNULL 指针,则调用无效参数处理程序,如参数验证中所述。 如果允许执行继续,则这些函数将返回 EOF 并将 errno 设置为 EINVAL

有关这些错误代码和其他错误代码的信息,请参阅 errno_doserrno_sys_errlist_sys_nerr

备注

scanf 函数从标准输入流 stdin 中读取数据,并将数据写入到 argument 指定的位置。 每个 argument 必须为指向类型的变量的指针,该类型与 format 中的类型说明符对应。 如果复制出现在重叠的字符串之间,则该行为不确定。

重要

使用 scanf 读取字符串时,请始终指定 %s 格式的宽度(例如 %32s 而不是 %s);否则,输入格式不正确很容易导致缓冲区溢出。 或者,请考虑使用 scanf_s_scanf_s_lwscanf_s_wscanf_s_lfgets

wscanfscanf的宽字符版本; formatwscanf 参数是宽字符字符串。 如果在 ANSI 模式下打开流,则 wscanfscanf 的行为相同。 scanf 当前不支持 UNICODE 流的输入。

这些带有 _l 后缀的函数的版本相同,只不过它们使用传递的区域设置参数而不是当前线程区域设置。

一般文本例程映射

TCHAR.H 例程 _UNICODE_MBCS 未定义 _MBCS 已定义 _UNICODE 已定义
_tscanf scanf scanf wscanf
_tscanf_l _scanf_l _scanf_l _wscanf_l

有关详细信息,请参阅格式规范字段:scanfwscanf 函数

要求

例程 必需的标头
scanf_scanf_l <stdio.h>
wscanf_wscanf_l <stdio.h><wchar.h>

通用 Windows 平台 (UWP) 应用中不支持控制台。 与控制台、stdinstdoutstderr 关联的标准流句柄必须重定向,然后 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_lfwscanf_fwscanf_l
printf_printf_lwprintf_wprintf_l
sprintf_sprintf_lswprintf_swprintf_l__swprintf_l
sscanf_sscanf_lswscanf_swscanf_l