scanf, wscanf
Read formatted data from the standard input stream. 从标准输入流读入格式化数据
int scanf( const char *format [,argument]... );
int wscanf( const wchar_t *format [,argument]... );
例行程序 必要的头文件 兼容性
Routine | Required Header | Compatibility |
scanf | <stdio.h> | ANSI, Win 95, Win NT |
wscanf | <stdio.h> or <wchar.h> | ANSI, Win 95, Win NT |
For additional compatibility information, see Compatibility in the Introduction
对于额外的兼容性信息,请参见兼容性的介绍
Return Value 返回值
Both scanf and wscanf return 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.
scanf函数和wscanf函数都会成功的返回字段值,并且进行转换和分配操作 ;如果返回值中不包括字段信息就只读取但不分配空间。返回值为0表示没有字段被分配。返回值为EOF表示返回一个错误信息或者是第一次尝试读取一个字符时却遇到了文件结束字符或者字符串结束字符
Parameters 参数
format 格式
Format control string 格式控制字符串
argument 参数
Optional arguments 可选参数
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.
scanf函数从标准输入设备(键盘)所输入的标准输入流中读取数据并把数据写入参数给出的指定位置 。每个参数都必须是一个指向变量类型的指针,即和格式说明符类型相匹配的指针。如果赋值字符串之间发生重叠,则为未定义行为。
wscanf是一个宽字符版本的scanf, wscanf的格式参数是一个宽字符的字符串。 wscanf和scanf其他方面的特性完全相同。
Example:
#include <stdio.h>
int main(void)
{
int i_number, result;
float f_number;
char c_number, str[81];
wchar_t wc_str, ws_str[81];
printf( "\n\nEnter an int, a float, two chars and two strings\n");
result = scanf( "%d %f %c %C %s %S", &i_number, &f_number, &c_number, &wc_str, str, ws_str );
printf( "\nThe number of fields input is %d\n", result );
printf( "The contents are: %d %f %c %C %s %S\n", i_number, f_number, c_number, wc_str, str, ws_str);
wprintf( L"\n\nEnter an int, a float, two chars and two strings\n");
result = wscanf( L"%d %f %hc %lc %S %ls", &i_number, &f_number, &c_number, &wc_str, str, ws_str );
wprintf( L"\nThe number of fields input is %d\n", result );
wprintf( L"The contents are: %d %f %C %c %hs %s\n", i_number, f_number, c_number, wc_str, str, ws_str);
}
//VC++6.0
/***************************************************
Enter an int, a float, two chars and two strings
71
98.6
h
z
Byte charcaters
The number of fields input is 6
The contents are: 71 98.599998 h z Byte charcaters
Enter an int, a float, two chars and two strings
36
92.3
y
n
Wide characters
The number of fields input is 6
The contents are: 36 92.300003 y n Wide characters
Press any key to continue
***************************************************/