Latest web development tutorials

C library functions - scanf ()

C standard library - <stdio.h> C standard library - <stdio.h>

description

C library functionsint scanf (const char * format, ...) to read formatted input from stdin input standard.

statement

Here is () statement scanf function.

int scanf(const char *format, ...)

parameter

  • format - This is a C string containing the following items in one or more of:space characters, non-space charactersand format specifiers.
    format specifier of the form[=% [*] [width ] [modifiers] type =], the specific explanation as follows:
参数描述
*这是一个可选的星号,表示数据是从流 stream 中读取的,但是可以被忽视,即它不存储在对应的参数中。
width这指定了在当前读取操作中读取的最大字符数。
modifiers为对应的附加参数所指向的数据指定一个不同于整型(针对 d、i 和 n)、无符号整型(针对 o、u 和 x)或浮点型(针对 e、f 和 g)的大小: h :短整型(针对 d、i 和 n),或无符号短整型(针对 o、u 和 x) l :长整型(针对 d、i 和 n),或无符号长整型(针对 o、u 和 x),或双精度型(针对 e、f 和 g) L :长双精度型(针对 e、f 和 g)
type一个字符,指定了要被读取的数据类型以及数据读取方式。具体参见下一个表格。

scanf type specifier:

类型合格的输入参数的类型
c单个字符:读取下一个字符。如果指定了一个不为 1 的宽度 width,函数会读取 width 个字符,并通过参数传递,把它们存储在数组中连续位置。在末尾不会追加空字符。char *
d十进制整数:数字前面的 + 或 - 号是可选的。int *
e,E,f,g,G浮点数:包含了一个小数点、一个可选的前置符号 + 或 -、一个可选的后置字符 e 或 E,以及一个十进制数字。两个有效的实例 -732.103 和 7.12e4float *
o八进制整数。int *
s字符串。这将读取连续字符,直到遇到一个空格字符(空格字符可以是空白、换行和制表符)。char *
u无符号的十进制整数。unsigned int *
x,X十六进制整数。int *
  • Additional parameters - Depending on the format string, the function may require a series of additional parameters, each containing a value to be inserted, replacing the format specified in the parameters% each label.The number of parameters should be the same as the number of label%.

return value

If successful, the function returns the number of successfully matched and assigned. If you reach the end of the file or a read error occurs, it returns EOF.

Examples

The following example demonstrates the scanf () function is used.

#include <stdio.h>

int main()
{
   char str1[20], str2[30];

   printf("请输入用户名:");
   scanf("%s", &str1);

   printf("请输入您的网站:");
   scanf("%s", &str2);

   printf("输入的用户名:%s\n", str1);
   printf("输入的网站:%s", str2);
   
   return(0);
}

Let's compile and run the above program, which will produce the following results in interactive mode:

请输入用户名:admin
请输入您的网站:www.w3cschool.cc

输入的用户名:admin
输入的网站:www.w3cschool.cc

C standard library - <stdio.h> C standard library - <stdio.h>