目录
一.scanf的返回值:
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 表示错误,或者在第一次尝试读取字符时遇到文件结束字符或字符串结尾字符。
简单的来讲就是:
scanf函数返回的值是:实际读取到的数据的个数;
scanf函数读取失败的时候,返回的是EOF。
#include <stdio.h>
int main()
{
int a = 0, b = 0;
char c;
printf("%d\n", scanf("%d %d %c", &a,&b,&c));
return 0;
}
由下图可见当读取了三个数据的时候,scanf的返回值为3:
二.什么是EOF
EOF的全称是end of file,是文件结束的标志:
我们在VS2022中输入EOF,右击选择转到定义(要学习这种方法),可以看到EOF的实质就是-1。
三.关于scanf函数在多组输入中的应用
下面是对应实现的代码:
#include <stdio.h>
int main()
{
char a[200];
int i=0;
while(scanf("%c",&a[i])!=EOF)//这里便是实现多组输入的代码,只要读取成功,便会进入循环。
{
printf("%c\n",a[i]+32);
i++;
getchar();
}
return 0;
}
需要格外注意的是:
多组输入过程中要注意“回车”也是字母,所以要“吸收”(getchar())掉该字母。
需要注意的是在Windows环境下输入ctrl+z即可结束多组输入,至于输入几次是和编译器有关的在VS2022环境下需要输入两次
四.扩展了解
你可能还需要了解printf的返回值: