scanf, wscanf
Read formatted data from the standard input stream.
int scanf( const char *format [, argument]... ); int wscanf( const wchar_t *format [, argument]... );
Parameters
- format
- Format control string.
- argument
- Optional arguments.
Return Value
Returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end-of-file character or the end-of-string character is encountered in the first attempt to read a character.
Remarks
The scanf function reads data from the standard input stream stdin and writes the data into the location given by argument. Each argument must be a pointer to a variable of a type that corresponds to a type specifier in format. If copying takes place between strings that overlap, the behavior is undefined.
Security Note When reading a string with scanf, always specify a width for the %s format (for example,"32%s"instead of"%s"); otherwise, improperly formatted input can easily cause a buffer overrun. Alternately, consider using fgets.
wscanf is a wide-character version of scanf; the format argument to wscanf is a wide-character string. wscanf and scanf behave identically otherwise.
Generic-Text Routine Mappings
| TCHAR.H routine | _UNICODE & _MBCS not defined | _MBCS defined | _UNICODE defined |
|---|---|---|---|
| _tscanf | scanf | scanf | wscanf |
For more information, see Format Specification Fields — scanf functions and wscanf Functions.
Requirements
| Routine | Required header | Compatibility |
|---|---|---|
| scanf | <stdio.h> | ANSI, Win 98, Win Me, Win NT, Win 2000, Win XP |
| wscanf | <stdio.h> or <wchar.h> | ANSI, Win 98, Win Me, Win NT, Win 2000, Win XP |
For additional compatibility information, see Compatibility in the Introduction.
Libraries
All versions of the C run-time libraries.
Example
// crt_scanf.c
/* 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 );
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 );
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);
}
Input
71 98.6 h z Byte characters 36 92.3 y n Wide characters
Output
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
See Also
Floating-Point Support Routines, Stream I/O Routines, Locale Routines | fscanf | printf | sprintf | sscanf | Run-Time Routines and .NET Framework Equivalents