根据MSDN对getchar()的定义:
int getchar(void);
Each of these functions returns the character read. To indicate an read error or end-of-file condition, get and getchar return EOF, and getwc and getwchar return WEOF, for getc and getchar, use ferror or feof to chheck for an error or for end of file.
以及对scanf()的定义
int scanf();
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()输入成功时返回输入成功赋值的数据项数,失败则返回EOF。
EOF: End-Of-File 文件结束标志,本质上是-1。
char password[20] = { 0 };
printf("Input password:>");
scanf("%s", password);
printf("Confirm(Y/N):>");
int ch = getchar();
if ('Y' == ch)
printf("Confirm successfully");
else
printf("Cancceled");
运行结果:
原因
scanf()和getchar()是从缓冲区中读取数据的。当输入"123456n"时,scanf()会把123456读走,当按下回车键(即n)时,getchar()从缓冲区中将n读走,因此确认失败。
修正方法一:
...
getchar();
printf("Confirm(Y/N):>");
int ch = getchar();
if ('Y' == ch)
printf("Confirm successfully");
else
printf("Cancceled");
这种方法有缺陷,如果输入"123456 abcdefn"仍然会读取失败。scanf(“%s”)只会读取空格之前的字符串即"123456 “。getchar()只能处理接下来的"a”。
方法二:
int tmp = 0;
while ((tmp = getchar()) != 'n')
{
;
}
printf("Confirm(Y/N):>");
int ch = getchar();
if ('Y' == ch)
printf("Confirm successfully");
else
printf("Cancceled");
使用
连续读取:
while ((ch = getchar()) != EOF)
{
putchar(ch);
}
读取带空格的字符串等:
while ((tmp = getchar()) != 'n')
{
;
}
写法一:
while (EOF != scanf("%s", ch))
{
}
写法二:
while (~scanf("%s", ch))
这两种写法是一样的。scanf()输入错误返回的是-1。~scanf()指的就是当scanf()读到-1时,将-1按位取反,计算机中存储的是补码,即 ~11111111=00000000,此时while的判断条件为假跳出循环。



