一个简单的密码验证程序,为什么第一次输入错误第二次输入正确时没有提示密码正确?
#include<stdio.h>int main()
{
int i=0;
do
{
printf("请输入你的密码:\n");
i++;
if(getchar()!='z')
{
printf("再次输入你的密码:\n");
i++;
if(getchar()=='z')
{
printf("welcome!!\n");
}
if(getchar()!='z')
{
printf("exit\n");
}
}
else
{
printf("welcome!\n");
break;
}
}while(i<2);
return 0;
}
getchar提取字符也会提取回车'\n',因此每个判断都要有个getchar去吃掉缓冲区的'\n'
#include<stdio.h>
int main()
{
int i=0;
do
{
printf("请输入你的密码:\n");
i++;
if(getchar()!='z')
{
getchar();
printf("再次输入你的密码:\n");
i++;
if(getchar()=='z')
{
getchar();
printf("welcome!!\n");
}
if(getchar()!='z')
{
getchar();
printf("exit\n");
}
}
else
{
printf("welcome!\n");
break;
}
}while(i<2);
return 0;
}
好,我试试(▽) 小甲鱼的铁粉 发表于 2021-1-31 15:23
getchar提取字符也会提取回车'\n',因此每个判断都要有个getchar去吃掉缓冲区的'\n'
我研究了下网上的资料,发现只要在两个ch=getchar()之间加上一个getchar()就可以了。csdn上有人发了个有关这个的帖子
https://blog.csdn.net/u011562187/article/details/9955785?ops_request_misc=%25257B%252522request%25255Fid%252522%25253A%252522161210252216780274153741%252522%25252C%252522scm%252522%25253A%25252220140713.130102334..%252522%25257D&request_id=161210252216780274153741&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-9955785.pc_search_result_no_baidu_js&utm_term=%25E9%259C%2580%25E8%25A6%2581%25E7%2594%25A8getchar%2528%2529%25E5%2590%2583%25E6%258E%2589%25E5%259B%259E%25E8%25BD%25A6%25E7%259A%2584%25E5%2587%25A0%25E7%25A7%258D%25E6%2583%2585%25E5%2586%25B5%25E4%25B8%25AA%25E4%25BA%25BA%25E5%25AE%259E%25E9%25AA%258C%25E6%2580%25BB%25E7%25BB%2593
{:5_109:}
页:
[1]