scanf, _scanf_l, wscanf, _wscanf_lscanf, _scanf_l, wscanf, _wscanf_l
Lee datos con formato del flujo de entrada estándar.Reads formatted data from the standard input stream. Hay disponibles versiones más seguras de estas funciones; vea scanf_s, _scanf_s_l, wscanf_s, _wscanf_s_l.More secure versions of these function are available; see scanf_s, _scanf_s_l, wscanf_s, _wscanf_s_l.
Nota
En Visual Studio 2015 printf
, la scanf
familia de funciones y se declararon como inline
y se movieron a los <stdio.h>
<conio.h>
encabezados y.In Visual Studio 2015 The printf
and scanf
family of functions were declared as inline
and moved to the <stdio.h>
and <conio.h>
headers. Si va a migrar código anterior, es posible que vea LNK2019 en conexión con estas funciones.If you are migrating older code you might see LNK2019 in connection with these functions. Para obtener más información, vea Visual C++ historial de cambios 2003-2015.For more information, see Visual C++ change history 2003 - 2015.
SintaxisSyntax
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]...
);
ParámetrosParameters
formatformat
Cadena de control de formato.Format control string.
argumentargument
Argumentos opcionales.Optional arguments.
localelocale
Configuración regional que se va a usar.The locale to use.
Valor devueltoReturn Value
Devuelve el número de campos que se han convertido y asignado correctamente; el valor devuelto no incluye los campos que se leyeron pero no se asignaron.Returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. Un valor devuelto de 0 indica que no se ha asignado ningún campo.A return value of 0 indicates that no fields were assigned.
Si Format es un puntero nulo , se invoca el controlador de parámetros no válidos, tal y como se describe en validación de parámetros.If format is a NULL pointer, the invalid parameter handler is invoked, as described in Parameter Validation. Si la ejecución puede continuar, estas funciones devuelven EOF y establecen errno en EINVAL.If execution is allowed to continue, these functions return EOF and set errno to EINVAL.
Para obtener información sobre estos y otros códigos de error, vea _doserrno, errno, _sys_errlist y _sys_nerr.For information on these and other error codes, see _doserrno, errno, _sys_errlist, and _sys_nerr.
ObservacionesRemarks
La función scanf Lee los datos del flujo de entrada estándar stdin y escribe los datos en la ubicación proporcionada por el argumento.The scanf function reads data from the standard input stream stdin and writes the data into the location given by argument. Cada argumento debe ser un puntero a una variable de un tipo que se corresponda con un especificador de tipo en formato.Each argument must be a pointer to a variable of a type that corresponds to a type specifier in format. Si la copia tiene lugar entre cadenas que se superponen, el comportamiento es indefinido.If copying takes place between strings that overlap, the behavior is undefined.
Importante
Al leer una cadena con scanf, especifique siempre un ancho para el formato % s (por ejemplo, "% 32s" en lugar de "% s"); de lo contrario, la entrada con formato incorrecto puede producir fácilmente una saturación del búfer.When reading a string with scanf, always specify a width for the %s format (for example, "%32s" instead of "%s"); otherwise, improperly formatted input can easily cause a buffer overrun. Como alternativa, plantéese usar scanf_s, _scanf_s_l, wscanf_s, _wscanf_s_l o fgets.Alternately, consider using scanf_s, _scanf_s_l, wscanf_s, _wscanf_s_l or fgets.
wscanf es una versión con caracteres anchos de scanf; el argumento de formato para wscanf es una cadena de caracteres anchos.wscanf is a wide-character version of scanf; the format argument to wscanf is a wide-character string. wscanf y scanf se comportan exactamente igual si la secuencia se abre en modo ANSI.wscanf and scanf behave identically if the stream is opened in ANSI mode. scanf no admite actualmente la entrada desde un flujo Unicode.scanf doesn't currently support input from a UNICODE stream.
Las versiones de estas funciones con el sufijo _L son idénticas, salvo que utilizan el parámetro de configuración regional que se pasa en lugar de la configuración regional del subproceso actual.The versions of these functions with the _l suffix are identical except that they use the locale parameter passed in instead of the current thread locale.
Asignaciones de rutina de texto genéricoGeneric-Text Routine Mappings
Rutina TCHAR.HTCHAR.H routine | _UNICODE y _MBCS no definidos_UNICODE & _MBCS not defined | _MBCS definido_MBCS defined | _UNICODE definido_UNICODE defined |
---|---|---|---|
_tscanf_tscanf | scanfscanf | scanfscanf | wscanfwscanf |
_tscanf_l_tscanf_l | _scanf_l_scanf_l | _scanf_l_scanf_l | _wscanf_l_wscanf_l |
Para obtener más información, vea campos de especificación de formato: funciones scanf y funciones wscanf.For more information, see Format Specification Fields — scanf functions and wscanf Functions.
RequisitosRequirements
RutinaRoutine | Encabezado necesarioRequired header |
---|---|
scanf, _scanf_lscanf, _scanf_l | <stdio.h> |
wscanf, _wscanf_lwscanf, _wscanf_l | <stdio.h> o <wchar.h><stdio.h> or <wchar.h> |
La consola no se admite en aplicaciones de Plataforma universal de Windows (UWP).The console is not supported in Universal Windows Platform (UWP) apps. Los identificadores de flujo estándar que están asociados a la consola, stdin, stdout y stderr deben redirigirse antes de que las funciones en tiempo de ejecución de C puedan usarlos en aplicaciones para UWP.The standard stream handles that are associated with the console, stdin, stdout, and stderr, must be redirected before C run-time functions can use them in UWP apps. Para obtener información adicional sobre compatibilidad, consulte Compatibilidad.For additional compatibility information, see Compatibility.
EjemploExample
// 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
Consulte tambiénSee also
Compatibilidad de punto flotanteFloating-Point Support
E/S de secuenciaStream I/O
Configuración regionalLocale
fscanf, _fscanf_l, fwscanf, _fwscanf_lfscanf, _fscanf_l, fwscanf, _fwscanf_l
printf, _printf_l, wprintf, _wprintf_lprintf, _printf_l, wprintf, _wprintf_l
sprintf, _sprintf_l, swprintf, _swprintf_l, _ _swprintf_lsprintf, _sprintf_l, swprintf, _swprintf_l, __swprintf_l
sscanf, _sscanf_l, swscanf, _swscanf_lsscanf, _sscanf_l, swscanf, _swscanf_l