代码:
#include <stdio.h>
int main() {
// ret 记录getchar数据
int ret = 0;
// password 记录scanf数据
char password[20] = {0};
printf("Input Passsword:");
scanf("%s", password);
printf("\n");
printf("Verify Password:");
ret = getchar();
if (ret == "Y") {
printf("OK\n");
} else {
printf("Not OK\n");
}
return 0;
}
问题描述:
按要求输入123后,确认密码阶段,程序未等待,直接输出提示并结束程序
debug发现,结束程序时,ret值为10
解释:
scanf与getchar为输入函数,输入内容存放在输入缓冲区中,键入123
后,缓冲区实际内容为123\n
,其中\n
触发scanf读取缓冲区内容,scanf读取\n
之前内容,缓冲区剩余\n
,非空,被getchar读取后,结束程序。
解决:
增加getchar
以清空缓冲区
#include <stdio.h>
int main() {
// ret 记录getchar数据
int ret = 0;
// password 记录scanf数据
char password[20] = {0};
printf("Input Passsword:");
scanf("%s", password);
// 输入缓冲区剩余‘\n’
// 由getchar读取,清空输入缓冲区
getchar();
printf("\n");
printf("Verify Password:");
ret = getchar();
if (ret == "Y") {
printf("OK\n");
} else {
printf("Not OK\n");
}
return 0;
}
问题描述2:
当输入内容包含空格时,上述解决方案复现前述问题。
解决
#include <stdio.h>
int main() {
// ret 记录getchar数据
int ret = 0;
// password 记录scanf数据
char password[20] = {0};
printf("Input Passsword:");
scanf("%s", password);
// 输入缓冲区剩余‘\n’
// 由getchar读取,清空输入缓冲区
while (getchar() != '\n'){
;
}
printf("\n");
printf("Verify Password:");
ret = getchar();
if (ret == "Y") {
printf("OK\n");
} else {
printf("Not OK\n");
}
return 0;
}