scanf() 函数定义在 stdio.h 头文件中。它有助于输入数据。它从 stdin 流读取格式化输入。
int scanf(const char *format, ...); #where format can be a integer, character, string, float
scanf() 函数接受一个格式字符串作为参数。它可以包含**空格字符**、**非空格字符**和**格式说明符**。格式说明符的格式为 **[=%[*][width][modifiers]cype=]。 **
* - 表示从流中读取数据但忽略它。
width - 指定当前读取操作中要读取的最大字符数。
modifiers - 对应附加参数指向的数据的类型:h: short int 或 unsigned short int,l: long int 或 unsigned long int 或 double,L: long double。
type - 一个字符,指定要读取的数据类型以及预期读取方式。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| format | 包含要写入 stdout 流的文本的字符串 | 必需 |
| additional arguments | 包含要替换格式参数中每个 %-tag 的值 | 可选 |
scanf() 函数的返回值是成功读取的字符总数,失败时返回 EOF。
| 输入 | 返回值 |
|---|---|
| 如果成功, | 字符总数 |
| 如果读取错误或达到 EOF | 返回 EOF |
#include <stdio.h>
int main()
{
char st1[25], st2[25];
printf("Enter Place: ");
scanf("%s", st1);
printf("Enter your name: ");
scanf("%s", st2);
printf("Entered Place is: %s\n", st1);
printf("Entered Name is:%s", st2);
return(0);
}
输出
Enter Place:London Enter your name:Albert Entered Place is:London Entered Name is:Albert
#include <stdio.h>
int main (){
int x;
printf("Enter the value of x:");
scanf("%d", &x);
printf("The value of x is: %d", x);
return 0;
}
输出
Enter the value of x: 12 The value of x is: 12