scanf()
是 C 和 C++ 标准库中的一个输入函数,同样位于 <cstdio>
头文件里,其功能是按照指定格式从标准输入设备(通常是键盘)读取数据。下面为你详细介绍 scanf()
函数的相关知识点。
1. 基本使用
scanf()
函数的基本语法如下:
cpp
#include <cstdio>
int main() {
int num;
printf("Please enter an integer: ");
scanf("%d", &num); // 读取一个整数到变量 num 中
printf("You entered: %d\n", num);
return 0;
}
在这个例子中,scanf()
函数的第一个参数是格式字符串 "%d"
,它表示要读取一个十进制整数。第二个参数 &num
是变量 num
的地址,scanf()
会把读取到的数据存储到该地址对应的内存空间中。
2. 格式说明符
scanf()
使用的格式说明符和 printf()
类似,用于指定要读取的数据类型。常见的格式说明符如下:
格式说明符 | 描述 |
---|---|
%d 或 %i | 读取十进制整数 |
%u | 读取无符号十进制整数 |
%f | 读取浮点数 |
%c | 读取单个字符 |
%s | 读取字符串(以空白字符结束) |
%x 或 %X | 读取十六进制整数 |
示例代码:
cpp
#include <cstdio>
int main() {
int num;
float float_num;
char ch;
char str[100];
printf("Enter an integer: ");
scanf("%d", &num);
printf("Enter a float: ");
scanf("%f", &float_num);
printf("Enter a character: ");
scanf(" %c", &ch); // 注意前面的空格,用于消耗掉之前输入的换行符
printf("Enter a string: ");
scanf("%s", str); // 不需要取地址符,因为数组名本身就是地址
printf("You entered: %d, %f, %c, %s\n", num, float_num, ch, str);
return 0;
}
3. 读取多个数据
scanf()
可以同时读取多个数据,只需在格式字符串中使用多个格式说明符,并提供相应数量的变量地址。
cpp
#include <cstdio>
int main() {
int a, b;
printf("Enter two integers separated by a space: ");
scanf("%d %d", &a, &b);
printf("You entered: %d and %d\n", a, b);
return 0;
}
4. 返回值
scanf()
函数会返回成功匹配并赋值的输入项数量。如果到达文件末尾或者发生读取错误,则返回 EOF
(通常为 -1)。
cpp
#include <cstdio>
int main() {
int a, b;
int result = scanf("%d %d", &a, &b);
if (result == 2) {
printf("Successfully read two integers.\n");
} else if (result == EOF) {
printf("Reached end of file.\n");
} else {
printf("Error reading input.\n");
}
return 0;
}
5. 注意事项
- 取地址符:除了字符串数组(因为数组名本身就是地址),对于其他变量,必须使用取地址符
&
来传递变量的地址。 - 空白字符处理:
scanf()
在读取除%c
之外的格式说明符时,会自动跳过空白字符(如空格、制表符、换行符)。但对于%c
,它会读取下一个字符,包括空白字符。为了避免这种情况,你可以在%c
前面加一个空格,用于消耗掉之前输入的换行符。 - 缓冲区问题:如果输入的数据格式与格式说明符不匹配,可能会导致输入缓冲区中残留数据,影响后续的输入操作。你可以通过手动清空输入缓冲区来避免这种问题。
cpp
#include <cstdio>
void clearInputBuffer() {
int c;
while ((c = getchar()) != '\n' && c != EOF);
}
int main() {
int num;
printf("Enter an integer: ");
if (scanf("%d", &num) != 1) {
printf("Invalid input. Please enter an integer.\n");
clearInputBuffer();
} else {
printf("You entered: %d\n", num);
}
return 0;
}
以上就是 scanf()
函数的主要知识点,通过合理使用这些知识,你可以实现从标准输入读取不同类型数据的功能。